Setting cookies in the Python Flask framework is a straightforward process. I'll walk you through the steps to set cookies:
1. Import the Flask Library
First, import the Flask and make_response classes from the flask module.
pythonfrom flask import Flask, make_response
2. Create a Flask Application Instance
Next, create a Flask application instance.
pythonapp = Flask(__name__)
3. Define Routes and View Functions
Define a route and its corresponding view function where you set the cookie.
python@app.route('/') def index(): resp = make_response('Cookie is set') resp.set_cookie('your_cookie_name', 'your_cookie_value') return resp
In this example, when a user accesses the root directory of the website (i.e., '/'), the index function is invoked. Here, we first create a response object resp containing the text response for the user ('Cookie is set'). Then, use the resp.set_cookie method to set a cookie. The first parameter is the cookie's name, and the second parameter is the cookie's value.
4. Run the Flask Application
Finally, run the Flask application to enable it to handle requests and set cookies.
pythonif __name__ == '__main__': app.run(debug=True)
Thus, when you access this application, Flask automatically handles cookie setting.
Example: Setting Cookie Expiration Time
You can also set other cookie attributes, such as expiration time. This is achieved using the max_age parameter, which specifies the cookie's duration in seconds.
python@app.route('/set_cookie') def set_cookie(): resp = make_response("Cookie with expiration is set") resp.set_cookie('your_cookie_name', 'your_cookie_value', max_age=60*60*24*7) # Expiration time: one week return resp
In this example, the cookie's expiration time is set to one week.
By following this approach, you can flexibly set and manage cookies within your Flask application.