Welcome to our Flask Tutorials! Today, we'll dive into understanding the lifecycle of a request in a Flask application. 📝
Flask is a micro web framework written in Python. It's easy to use, lightweight, and perfect for building web applications.
A Flask application's lifecycle consists of a series of events triggered by a client's request. Let's break it down:
Before a request is handled, Flask performs several tasks:
WsgiRequest object to store the incoming request data.Response object that will hold the response to send back to the client.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.
@app.route('/')
def home():
return "Welcome to CodeYourCraft!"Once the request is handled, Flask performs some cleanup tasks:
WsgiRequest object to free up memory.Let's create a simple Flask application that takes user input and stores it in a database.
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.
What happens during the Before Request phase in a Flask application?