Sign In
Sign In

How to Handle Incoming Request Data in Flask

How to Handle Incoming Request Data in Flask
Hostman Team
Technical writer
Flask
15.10.2024
Reading time: 6 min

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:

  1. Accept the request.
  2. Choose a request handler.
  3. Execute the handler.
  4. 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

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.

  1. Install Python. Visit the official website www.python.org/downloads, choose the Python version for your OS, and follow the installer instructions.

  1. Install pipenv. Pipenv is 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
  1. Install PyCharmPyCharm is 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

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

After creating the project, open the terminal at the bottom of PyCharm and run:

pip install flask

If 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 RemoteSigned

Then type [A] to allow the script to run.

Working with URLs

Once the necessary components are installed, let's start interacting with Flask. First, import Flask:

from flask import Flask

We’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 .route decorator to assign functions to specific URLs.

  • Finally, we run the application using app.run().

Running the Application

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

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.10

Here, 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:

  1. Imports the request class and its methods.

  2. Uses the .args.get() method to extract query parameters.

  3. 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.10

The application will correctly process the GET request and display the extracted parameters.

Handling POST Requests

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:

  1. The decorator handles both GET and POST requests.

  2. On a GET request, a form for login and password is displayed.

  3. 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/authorization

If you enter "admin" as both login and password, you will see "Correct." Otherwise, you’ll see "Incorrect."

Full Code Example

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

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.

Flask
15.10.2024
Reading time: 6 min

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start
Email us