flask set cookie
To set a cookie in Flask, you can follow these steps:
Import the necessary modules: Begin by importing the required module,
flask
. This module contains the necessary functions and classes to handle cookies in Flask.Create a Flask application: Next, create a Flask application object using the
Flask
class. This object will be used to handle requests and responses in your Flask application.Set the cookie: To set a cookie, you can use the
set_cookie
method provided by the Flask application object. This method takes several parameters, including the name of the cookie, its value, and optional parameters such as the maximum age and path.Return the response: After setting the cookie, you need to return a response to the client. This can be done using the
make_response
function from theflask
module. This function takes the cookie and creates a response object that can be sent back to the client.
Here is an example of how these steps can be implemented in Python code:
from flask import Flask, make_response
# Create the Flask application
app = Flask(__name__)
# Set the cookie
@app.route('/')
def set_cookie():
response = make_response('Cookie has been set!')
response.set_cookie('my_cookie', 'cookie_value', max_age=3600, path='/')
return response
if __name__ == '__main__':
app.run()
In this example, the set_cookie
function is decorated with the @app.route('/')
decorator, which means that it will be called when a request is made to the root URL ("/"). The make_response
function is used to create a response object, and the set_cookie
method is used to set the "my_cookie" cookie with a value of "cookie_value", a maximum age of 3600 seconds (1 hour), and a path of "/".
Please note that this example assumes you have Flask installed and configured properly. You may need to adjust the code to fit your specific Flask application.