24 Simple Web-Based Application

From Waveshare Wiki
Jump to: navigation, search

In the previous chapters, we introduced how to use Flask to achieve low-latency image transmission, which is used to transfer the camera feed to the web application interface. Here, we will discuss how to pass the information entered on the web application interface to the backend of the web application. This functionality is used to control the robot using the web application.

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == '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's 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 encounter a port conflict, it means you've previously run this code block. You'll need to click "Kernel" in the JupyterLab menu bar and then select "Shut Down All Kernels" to release the resources, including network port resources, occupied by the previously run code block. After that, you can rerun the code block to run this Flask application.

Once you run the code block, you'll see messages like "Running on http://127.0.0.1:5000" and "Running on http://[IP]:5000". Usually, the "[IP]" here refers to the IP address assigned to your Raspberry Pi by your router. You can open a web browser on any device within the same local network and visit "[IP]:5000". Note that the ':' symbol here must be the English colon, representing the port number 5000 of the IP address you're accessing.

Upon visiting this page, you'll see an input box and a "Submit" button. You can enter some content into the input box and then click the "Submit" button. After that, you can see the content you entered on the web page, and the backend will display the content it received below the code block in JupyterLab.