📜  python session set cookies - Python (1)

📅  最后修改于: 2023-12-03 15:04:08.516000             🧑  作者: Mango

Python Session Set Cookies

Cookies are small data files that are stored on a user's computer by a website in order to remember certain information about the user. Cookies can be used for a variety of purposes such as remembering user preferences or login information. In Python, cookies can be set and accessed using sessions.

Setting Cookies

To set a cookie using sessions in Python, we first need to import the flask module and create a flask app:

from flask import Flask, session
app = Flask(__name__)

Next, we need to set a secret key for the app:

app.secret_key = 'secret_key'

This is used to securely sign the session cookies. Note that the secret key should be kept secret and never shared.

We can now set a cookie using the session object:

@app.route('/')
def index():
    session['username'] = 'john'
    return 'Cookie set!'

This code sets a cookie with the key 'username' and the value 'john'.

Accessing Cookies

To access the cookie we just set, we can simply retrieve the value from the session object:

@app.route('/')
def index():
    username = session.get('username')
    return f'Hello, {username}!'

This code retrieves the value of the cookie with the key 'username' using the get method and stores it in a variable called username. We can then use this value in our response.

Expire Cookies

Cookies can also be set to expire after a certain amount of time. We can set the expiration time as follows:

from datetime import timedelta

@app.before_request
def make_session_permanent():
    session.permanent = True
    app.permanent_session_lifetime = timedelta(minutes=30)

@app.route('/')
def index():
    session['username'] = 'john'
    return 'Cookie set!'

This code sets the permanent attribute of the session object to True and sets the permanent_session_lifetime attribute of the app object to 30 minutes. This means that the cookie will expire after 30 minutes of inactivity.

Conclusion

In Python, cookies can be set and accessed using sessions. We can set cookies using the session object and retrieve the values using the get method. Cookies can also be set to expire after a certain amount of time.