Estimated reading time: 4 minutes
Here using Flask, Python’s package for web development, we will show you how to achieve this, and also explain the JSON output.
Where could this be useful?
(A) You want to pass data to a Python program to run a Machine Learning program you have written.
(B) You want to use Pythons functionality to add the data to a dashboard in real-time.
(C) Another use could be that you are in real-time processing requests on a website, but also want to use Python’s functionality to capture metrics on the data.
So how do we achieve this?
Step 1 – In Python create a Flask application
When you create a new Python file, the first step is to create add your import statements to the top of the file:
import json from flask import request from flask import Flask, render_template app = Flask(__name__)
As can be seen from the above, we bring in the flask package. This is now starting the process of creating a web development site.
Step 2 – Create the web route for telling the programme what the HTML template is called.
@app.route('/') def index(): return render_template('index.html')
Step 3 – Create the logic that will receive the data from the JSON on the website.
@app.route('/test', methods=['POST']) def test(): output = request.get_json() print(output) # This is the output that was stored in the JSON within the browser print(type(output)) result = json.loads(output) #this converts the json output to a python dictionary print(result) # Printing the new dictionary print(type(result))#this shows the json converted as a python dictionary return result
In the above we will explain the logic:
/test ===> this is what the page further on the logic will look to send the data entered on the website to.
methods=[‘POST’] ===> This is what it is looking out for when the JSON is been sent.
As can be seen in the function the rest of the code just retrieves the data and processes it.
Step 4 – Create the HTML file that will capture input and process the data to JSON.
The page looks like this:
The code behind this is as follows:
This block of code is HTML and runs as follows:
There are two input text boxes that take the data entered.
There is a button that when clicked, runs the function onclick=’myfunction();’
We then create a dictionary with those values.
Next, we create a variable that takes the dictionary and converts it into the JSON format.
The section starting with ” $.ajax“, creates the JSON and readies it to be passed to “/test” identified in step3.
STEP 5 – Where does this leave us?
So what does this all look like when completed?
The data first comes as JSON str and is then converted to a Python dictionary.
After this, you can then start manipulating the data in Python!