Flask Tutorials: Before and After Request 🎯

beginner
23 min

Flask Tutorials: Before and After Request 🎯

Welcome to our Flask Tutorials! Today, we'll dive into understanding the lifecycle of a request in a Flask application. 📝

What is Flask?

Flask is a micro web framework written in Python. It's easy to use, lightweight, and perfect for building web applications.

The Flask Request Lifecycle 📝

A Flask application's lifecycle consists of a series of events triggered by a client's request. Let's break it down:

Before Request 📝

Before a request is handled, Flask performs several tasks:

  1. It creates a new WsgiRequest object to store the incoming request data.
  2. It creates a Response object that will hold the response to send back to the client.
  3. It initializes a new app context, which allows us to access the application's globally-scoped objects, such as the database connection.

Request Handling 📝

Now comes the most important part: handling the request. This is where we define the logic for what happens when a user visits our application.

We do this by defining a function and decorating it with @app.route(). This function will be called when the corresponding URL is requested.

python
@app.route('/') def home(): return "Welcome to CodeYourCraft!"

After Request 📝

Once the request is handled, Flask performs some cleanup tasks:

  1. It clears the WsgiRequest object to free up memory.
  2. It destroys the app context to release any resources it was holding.

Real-World Example 💡

Let's create a simple Flask application that takes user input and stores it in a database.

python
from flask import Flask, request, db app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db.init_sqlalchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) @app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'POST': user = User(name=request.form['name']) db.session.add(user) db.session.commit() return "User {} added!".format(request.form['name']) return ''' <form method="post"> <p><input name="name"></p> <p><input type="submit" value="Submit"></p> </form> ''' if __name__ == "__main__": app.run(debug=True)

In this example, we have a User model that represents a user with a name. We define a route that handles both GET and POST requests. If the request is a POST request, we create a new user with the submitted name, save it to the database, and return a success message.

Quiz 🎯

Quick Quiz
Question 1 of 1

What happens during the Before Request phase in a Flask application?