25 Simple Web Application
Simple Web Application
In previous chapters, we introduced how to use Flask to achieve low‑latency video streaming, sending the camera feed to a web application interface. Here we describe how to pass information entered in the web application interface to the backend of the web application. This functionality can be used to control the robot via a web application.
from flask import Flask, request # import Flask class and request object from the flask package
app = Flask(__name__) # create a Flask application instance
@app.route('/', methods=['GET', 'POST']) # define the root route and allow GET and POST methods
def index():
if request.method == 'POST': # check whether the current request is POST
# get form data
form_data = request.form
# print form data
print(form_data)
# return a simple response
return 'Received data: {}'.format(form_data)
else:
# if it is a GET request, return a simple form page
return '''
<form method="post">
<label for="input_data">Input data:</label><br>
<input type="text" id="input_data" name="input_data"><br>
<input type="submit" value="Submit">
</form>
'''
if __name__ == '__main__':
app.run(host='0.0.0.0')
You can select the code block above and press Ctrl+Enter to run it. If you are prompted that the port is already in use, it means you have run this code block before. You need to click Kernel → Shut Down All Kernel in JupyterLab, which will release the resources (including network port resources) occupied by the previous run. Then you can re‑run the code block to start this Flask application.
After you run this code block, you will see lines like "Running on http://127.0.0.1:5000", "Running on http://[IP]:5000". Usually this [IP] is the IP address assigned to your Raspberry Pi by your router. You can open a browser on a device within the same local network and visit [IP]:5000. Note that the ':' symbol must be an English colon, indicating that you are accessing port 5000 of that IP address. After accessing this page, you will see an input box and a Submit button below. You can enter some content in the input box and then click the Submit button. Afterwards, you will see the content you entered on the web page displayed below the code block in JupyterLab, and the web page will also show the data received by the backend.