Today let’s briefly see how to create a simple WebApp using Flask the Python library that responds to GET and POST requests.
Flask is a web micro-framework written in Python, based on the Werkzeug WSGI tool and with the Jinja2 template engine. It is a micro-framework since it does not require any special tools or libraries.
Python Flask WebApp
Our Web application is very simple, the goal is to give you a clear and essential idea of the basics offered by Flask to be able to write complex applications.
In this example, we want to create a server that remains listening on port 8080 and responds to the resource /login to which, either through GET or POST requests, we will send a username (user) and password (pass).
First of all, let’s start by importing the Flask library in line 1. Then, in line 3, we define the resource on which the server will have to remain listening, namely /login. We also define what kind of requests it should handle, in this case both GET and POST.
Immediately below, we find the signature of the function used to receive the requests. Here it is not important that the function name is the same as the one specified in line 3, the essential thing is that it is located just below the @app.route decorator.
Inside the function we have access to several elements, the most important is the request that allows us to understand what kind of request we are dealing with. In line 5, we make sure that it is a POST, in that case we retrieve the parameters user and pass through the instructions 6 and 7.
Vice versa, in the case of a GET request, the instructions to access the parameters change slightly and are visible in lines 9 and 10.
Finished with the handling, we focus now on returning a necessary code for the client that sent the request. This is possible by using the Request object and specifying the return code.
To finish, in line 16, you can launch the server by specifying the port where it should remain listening.
A Brief Note
It’s worth making a note: launching the script in this way, the server will be reachable only from the device on which it is running, in my case at the address:
if however we wanted to reach the resource from another device connected to our same network, it is necessary to modify line 16 in the following way:
By doing so, Flask will allow us to reach the server by replacing localhost with the IP address of the device on which the server is running.
Conclusions
In this short tutorial, we saw how quick and easy it is to set up a server that responds to HTTP requests.
Flask is certainly a very versatile and resourceful tool. To learn more about its use, I suggest you take a look at the official documentation available at this address.
Leave A Comment