📜  Flask “ Cookies(1)

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

Flask - Cookies

Flask is a micro web framework written in Python. It is used to build web applications. Flask provides a mechanism to store and retrieve Cookies on the client-side. Cookies are small pieces of data that are stored on the client-side by the web server.

What are Cookies?

Cookies are small pieces of data that are stored on the client-side by the web server. They are used to store information about the user session or any other relevant information that needs to be accessed by the web server.

How to use Cookies in Flask?

To use cookies in Flask, you need to import the request and make_response modules from Flask. The request module is used to retrieve the cookies stored on the client-side. The make_response module is used to create a response object and set the cookies to be sent to the client-side.

Here's an example:

from flask import Flask, request, make_response

app = Flask(__name__)

@app.route('/')
def index():
    # set a cookie with a name and value
    resp = make_response('Setting a cookie')
    resp.set_cookie('name', 'value')
    return resp

@app.route('/getcookie')
def getcookie():
    # retrieve the value of a cookie
    name = request.cookies.get('name')
    return 'The value of the cookie is ' + name

In this example, we have defined two routes. The first route sets a cookie with a name and value. The second route retrieves the value of the cookie.

Conclusion

Cookies are an essential part of web applications. They are used to store information about the user session or any other relevant information that needs to be accessed by the web server. Flask provides a mechanism to store and retrieve Cookies on the client-side.