How to Handle Incoming Request Data in Flask
Websites where you watch videos, read news or chat with friends operate on a client-server architecture. The client (e.g., a browser) sends a request to the server, and based on that request, the server responds—usually by sending an HTML document back.
When we look under the hood of how websites work, request handling follows a general logic:
- Accept the request.
- Choose a request handler.
- Execute the handler.
- Send a response back to the client.
A framework is a developer tool used to implement this logic.
Flask is a microframework for building websites using Python. The term "micro" means that Flask provides a small, lightweight set of tools that are still sufficient for creating most websites. Flask is great for building APIs or websites hosted on cloud servers. In this article, we'll create a Flask application and explore how to process incoming requests.
Getting Started Copy link
We'll use PyCharm + pipenv on Windows 10. There are plenty of tutorials online for installing this setup on other operating systems, but here’s how to install it on Windows 10.
-
Install Python. Visit the official website www.python.org/downloads, choose the Python version for your OS, and follow the installer instructions.
-
Install pipenv.
Pipenvis a package for managing virtual environments in Python. To install it, open the Windows command prompt and run this command:
py -m pip install pipenv-
Install PyCharm.
PyCharmis an IDE (Integrated Development Environment) for Python. Download and install it from the official site www.jetbrains.com/pycharm, choosing either the Community or Professional version.
Creating a Project Copy link
In PyCharm, click "File" → "New Project" and specify the following:
- Project directory
- Virtual environment settings
- Path to the Python interpreter
- Path to pipenv executable
After setting everything up, click "Create."
Installing Flask Copy link
After creating the project, open the terminal at the bottom of PyCharm and run:
pip install flaskIf everything is set up correctly, Flask will install. If you encounter an error like "Execution of scripts is disabled," open PowerShell as an administrator and run this command:
Set-ExecutionPolicy RemoteSignedThen type [A] to allow the script to run.
Working with URLs Copy link
Once the necessary components are installed, let's start interacting with Flask. First, import Flask:
from flask import FlaskWe’ll write a small Flask application to demonstrate working with URL requests:
from flask import Flask
app = Flask(__name__)
@app.route("/hostman")
def hostman():
return "This is the /hostman page"
@app.route("/blog")
def blog():
return "This is the /blog page"
@app.route("/cloud")
def cloud():
return "This is the /cloud page"
if __name__ == "__main__":
app.run()
Explanation:
-
First, we import Flask.
-
We then create an instance of the Flask class,
app. -
We use the
.routedecorator to assign functions to specific URLs. -
Finally, we run the application using
app.run().
Running the Application Copy link
In the terminal, you will see the local address of your site (127.0.0.1:5000). You might see nothing if you navigate to this address because we still need to define a handler for the root URL (/). However, if you visit:
-
127.0.0.1:5000/hostman -
127.0.0.1:5000/blog -
127.0.0.1:5000/cloud
You’ll see responses for these routes. Flask automatically logs each request in the console.
Handling GET Requests Copy link
You can pass various parameters to the server via a GET request. For instance, consider this URL:
hostman.com/blog?framework=flask&language=python&version=3.10Here, the parameters are passed as key-value pairs after the question mark (?):
-
framework=flask -
language=python -
version=3.10
Let’s write a function, get_example(), to extract these parameters in Flask:
from flask import request
@app.route("/get_example")
def get_example():
framework = request.args.get('framework')
language = request.args.get('language')
version = request.args.get('version')
return f"language = {language}; framework = {framework}; version = {version}"
This code:
-
Imports the request class and its methods.
-
Uses the
.args.get()method to extract query parameters. -
Returns the extracted values in the response.
If you go to the URL:
http://127.0.0.1:5000/get_example?language=python&framework=flask&version=3.10The application will correctly process the GET request and display the extracted parameters.
Handling POST Requests Copy link
By default, .route() handles only GET requests. Flask can also handle POST requests. Let’s add a simple login form that accepts a username and password:
@app.route('/authorization', methods=['GET', 'POST'])
def authorization():
if request.method == 'POST':
login = request.form.get('Login')
password = request.form.get('Password')
if login == "admin" and password == "admin":
return "Correct"
else:
return "Incorrect"
return '''
<form method="POST">
<div><label>Login: <input type="text" name="Login"></label></div>
<div><label>Password: <input type="text" name="Password"></label></div>
<input type="submit" value="Enter">
</form>'''
Explanation:
-
The decorator handles both GET and POST requests.
-
On a GET request, a form for login and password is displayed.
-
On a POST request (when the form is submitted), the credentials are checked. If correct, it returns "Correct"; otherwise, it is "Incorrect."
Visit the URL:
127.0.0.1:5000/authorizationIf you enter "admin" as both login and password, you will see "Correct." Otherwise, you’ll see "Incorrect."
Full Code Example Copy link
from flask import Flask, request
app = Flask(__name__)
@app.route("/hostman")
def hostman():
return "This is the /hostman page"
@app.route("/blog")
def blog():
return "This is the /blog page"
@app.route("/cloud")
def cloud():
return "This is the /cloud page"
@app.route("/get_example")
def get_example():
framework = request.args.get('framework')
language = request.args.get('language')
version = request.args.get('version')
return f"language = {language}; framework = {framework}; version = {version}"
@app.route('/authorization', methods=['GET', 'POST'])
def authorization():
if request.method == 'POST':
login = request.form.get('Login')
password = request.form.get('Password')
if login == "admin" and password == "admin":
return "Correct"
else:
return "Incorrect"
return '''
<form method="POST">
<div><label>Login: <input type="text" name="Login"></label></div>
<div><label>Password: <input type="text" name="Password"></label></div>
<input type="submit" value="Enter">
</form>'''
if __name__ == "__main__":
app.run()
Conclusion Copy link
This article explored how to handle GET and POST requests in Flask. However, it's important to remember that security is critical when handling client data. Always validate and sanitize input to prevent malicious attacks. Prevention is the best way to protect your server from unwanted consequences.