Skip to Main Content
 

Blog title

Binubuo and Flask Tutorial - Using Binubuo in your development process

INFO_LIST

  • Author Head Binubuo
  • Category Binubuo API
  • Created Sun, Mar 05 2023
 

blog sections

Besides creating random synthetic data directly to your browser or to files, we want to show you how you can use Binubuo to help make your development process even better.

We will create a small application using the popular Python Flask framework https://flask.palletsprojects.com/, and we will use the synthetic dataset features to instantly have synthetic data that we can use directly in our application. We will show and explain how you can "evolve" your dataset automatically while your application is slowly developing and growing as well.

To follow along and doing your own code, you need to install Python 3 and Flask, as well as have some basic knowledge about Python. Digital Ocean has a nice guide on how to install the required components: https://www.digitalocean.com/community/tutorials/how-to-create-your-first-web-application-using-flask-and-python-3

Our sample application will be a small web shop called "Max Inc.". The first page we will build is the landing page with our products. For that we need to load some product data. In the production version it will load from the "real" web service, but while we are developing we will use the automatically created REST endpoints that we get when we create custom Binubuo Datasets.

So let us go and create a product dataset in the UI Builder.

If you want to create the dataset through the API instead the JSON template for the synthetic dataset is here:

{
    "columns": [
        {
            "column_name": "product_id",
            "column_type": "builtin",
            "column_datatype": "number",
            "builtin_type": "numiterate",
            "builtin_startfrom": "1",
            "builtin_increment_min": "1",
            "builtin_increment_max": "1"
        },
        {
            "column_name": "product_name",
            "column_datatype": "string",
            "column_type": "generated",
            "generator": "company_random.r_product_name"
        },
        {
            "column_name": "product_code",
            "column_datatype": "string",
            "column_type": "generated",
            "generator": "company_random.r_product_code"
        },
        {
            "column_name": "product_description",
            "column_datatype": "string",
            "column_type": "generated",
            "generator": "text_random.r_sentence"
        },
        {
            "column_name": "price",
            "column_datatype": "number",
            "column_type": "generated",
            "generator": "finance_random.r_amount",
            "arguments": " r_min => 200, r_max => 500"
        }
    ]
}

Now that we have built the dataset, and it is published with a REST interface, we can use it directly in our application. At first we will use the requests library to call the API, and then later we will show how you can use the Binubuo client as well.

Now we can create the Flask application file itself. Open a file called maxinc.py and put the following piece of code. We will create a generic function to fetch data, that will fetch it differently depending on what environment you are in. So if it is development/test/staging it will fetch from Binubuo, but if it is production environment it will fetch from your production endpoint.

from flask import Flask, render_template
import requests

app = Flask(__name__)

# Some application level settings
run_environment = 'Dev'

# Binubuo settings
my_key = 'YOUR_BINUBUO_KEY_HERE'
product_count = 25

def getPageData(restURL, rows=None):
    pageData = None
    if run_environment == 'Prod':
        # This is where you call your real API
        pass
    else:
        request_header = {'x-binubuo-key': my_key}
        # Parameters
        if rows is not None:
            params = dict()
            params["rows"] = rows
            response = requests.get(restURL, headers=request_header, params=params)
        else:
            response = requests.get(restURL, headers=request_header)
        pageData = response.json()
    return pageData

@app.route('/')
@app.route('/products/')
def products_home():
    maxinc_products = getPageData('https://binubuo.com/api/data/custom/YOUR_UNIQUE_URL_HASH/products', product_count)
    return render_template('products.html', product_list=maxinc_products)

Remember to change YOUR_BINUBUO_KEY_HERE to your own Binubuo API key and change YOUR_UNIQUE_URL_HASH which you can find under the details page of your dataset.

For the application itself, we need to build the first page. We will list all the products we have for now, and then later we will add the detail page for each product.

Flask uses templates to show the actual HTML page, and they are stored in a directory called templates. So create the templates directory in the same directory where you stored the maxinc.py file; and in the directory create a file called products.html with the following contents:

<title>Welcome to MaxInc Products</title>
<ul>
{% for product in product_list %}
    <li>{{ product.product_name }}</li>
{% endfor %}
</ul>

So now we are ready to start the Flask application and try it out for the first time. To start the development server type the following command from where you saved the maxinc.py file:

python -m flask --app maxinc run

By default the application will run on your local ip 127.0.0.1 and port 5000, so to access the application, open this URL in your local browser:

http://127.0.0.1:5000/

What you should see in your browser is a list of 25 synthetic product names generated by Binubuo (see picture and video below). Every time you refresh the screen it will be 25 new product names. We will learn later how you can keep the same names, for certain types of tests or validations where you need to repeat the same actions with the same values.

Screenshot showing the first page, listing 25 products, in the tutorial application being build.

So what if we wanted to create a detailed page for every product? Well for that we would need a new template for the application, and we would need the ability to query the API with a detailed request, so that we only fetch one specific product. Luckily when we create an API in binubuo, both endpoints gets deployed automatically. We simply use the first column as the key to a detailed query. So instead of calling (API basic endpoint) we can call (API/column_name/<product_id>) to get a detailed response of a single product. You can get the full link details under the Dataset information page:

Screenshot showing how to get the detail id url path on the dataset information page.

This means that we can now change the existing template for products list, to include a link to a product specific page. Change this line in the products.html file under the templates directory:

<li>{{ product.product_name }}</li>

into this:

<li><a href="/products/{{ product.product_id }}">{{ product.product_name }}</a></li>

And we also add a new page template called product.html, which will call the individual detail url for a specific product and show the detailed data:

<title>MaxInc Product: {{ product.product_name }}</title>
<div><span style="font-weight: bold;">Product Name: </span>{{ product.product_name }}</div>
<div><span style="font-weight: bold;">Product Description: </span>{{ product.product_description }}</div>
<div><span style="font-weight: bold;">Product Code: </span>{{ product.product_code }}</div>
<div><span style="font-weight: bold;">Price: </span>${{ product.price }}</div>

So now we can restart our application and check that our changes have worked. Go to the terminal window where you started the application and press CTRL-C to stop the server and start it again:

python -m flask --app maxinc run

and then open the start URL in the browser again:

http://127.0.0.1:5000/

The first page should now list our products as links, and if we click a link, we get to the detailed page showing us an individual products details.

Screenshot showing the product list as links.

Screenshot showing product detail page.

As you can see, Binubuo makes this very easy for you. No need to create more data, no time spent copying and pasting in a spreadsheet, no time fighting with insert statements in your database. Just quick and easy prototyping and ready to go.

When the times comes that you need to add more fields, you simply update your dataset and start showing that data in your application. So we pretend that we have gotten a change request, to add a product category to the list of products and also a rating of the product to the detailed page of the product. In a classic setup, you might then have to go to your development database, add the new columns, change your REST deployments and more; just to see if your code changes will work.

Not anymore with Binubuo. Simply go and update your dataset to include the new columns:

So now we can add the new column to our templates. We will change both the main page list in products.html and the detailed page in product.html to include the new product category field.

Change the products.html line from:

<li><a href="/products/{{ product.product_id }}">{{ product.product_name }}</a></li>

into this line:

<li><a href="/products/{{ product.product_id }}">{{ product.product_name }}</a> - {{ product.product_category }}</li>

and then in the product.html file, add the following line at the end:

<div><span style="font-weight: bold;">Product Category: </span>{{ product.product_category }}</div>

and after a restart of the application, we can go to the front page again and see that the category data has been added, and when we click to the detailed page, we can see the same has been added there.

Screenshot showing the product list as links and with the category text.

Screenshot showing product detail page with the category text added.

That's it for this time. In the next tutorial we will show you how you can take advantage of the locale parameter to test your applications Unicode capabilities and also how you can make sure that you get the same data every time you access the data.

If you want to just download all the code for the Flask application you can do so here: binubuo_flask_tutorial_1.zip

Remember to change API key and Unique url path in the maxinc.py file before you run it.

Don't have an account yet?

If you don't have an account on Binubuo yet, you can create one real quick. Just click "Prices and Registration" in the top right corner, and you are on your way to create all the synthetic data you could dream about.

Want to see how to get started: Get Started Guide

Get more guides and help from the blog

Youtube Channel

Follow Binubuo on Twitter:


If you already have an account on RapidAPI, you can use your account to access Binubuo

Connect on RapidAPI