For Raspberry Pi users, constructing a web application has now become easy with the support of Python Flask, which is a lightweight Python web framework that will let you create numerous web applications with ease. You don’t require any tools or dependencies to set up your application, as Python Flask will do it all by itself.
Setup Python Flask on Raspberry Pi
This article provides you with a detailed user guide on setting up Python Flask on Raspberry Pi. If you are interested in utilizing Python Flask to construct different applications, you must follow the below-given steps.
Step 1: Python Flask comes pre-installed in the Raspberry Pi OS, but if you still won’t be able to find it, you can execute the following command to install it successfully on your device.
First create a subfolder in your Documents folder, use the following command in the terminal.
Now create a directory with the name “rpiWebServer” using the following command.
Step 2: Next, in the “rpiWebServer” folder, you will need to create two subfolders namely the static folder for CSS and JavaScript files, and templates folder for HTML files. To do this, execute the below mentioned commands.
$ mkdir static
$ mkdir templates
Step 3: Now, you are good to create your first Python web server through Flask. To do it, open a new file in any Python IDE (Thonny) on your Raspberry Pi device and save it with a suitable name in the “rpiWebServer” folder.
Step 4: Now, copy the below given code and paste it into the Thonny IDE.
app = Flask(__name__)
@app.route('/')
def index():
return 'Welcome Linux Users'
if __name__ == '__main__':
app.run(debug=True, port=<Port number>, host='RaspberryPi Ip Address')
You can return any message you want or can paste your own code but the syntax would remain the same.
Also, you will need to check the port number of your Raspberry Pi and this can be done by executing the following script.
Step 5: Now, open your Raspberry Pi terminal, and run the code with the file name you have saved before using the following command (In our case it is Welcome.py):
Once it is done, you can then go on to your browser and enter the address that appears on the terminal with the port number. In our case it’s http://192.168.18.218:5000/. When you enter this address in your browser, you will see your message appear on the browser tab which you have included in your Python code.
In this way, you can run various Python codes whose output can easily be visualized on the browser tab. If you are creating a web application, you will need to first write a suitable code for it and then you can easily be able to host it on the web using the Python Flask.
Conclusion
Python Flask is an amazing micro web application framework which lets developers start building their web apps in a more effective and easy manner. This won’t require any extra tools or dependencies since it is very easy to set up on your Raspberry Pi device once you follow the aforementioned steps carefully.