This article is participating in Python Theme Month. See the link to the event for more details


Cookie and Session concepts

Cookie

In a web site, HTTP requests are stateless. That is, even after the first connection to the server and the login is successful, the second request server still cannot know which user is the current request. The appearance of cookie is to solve this problem. After the first login, the server returns some data (cookie) to the browser, and then the browser saves it locally. When the user sends a second request, the cookie data stored in the last request will be automatically carried to the server. The server uses the data carried by the browser to determine the current user.

Cookies store a limited amount of data. Different browsers have different storage sizes, but generally no more than 4KB.

Therefore, cookies can only store a small amount of data.


Session

Sessions are similar to cookies in that they store information about the user. The difference is that cookies are stored in the local browser, while sessions are stored on the server. Data stored on the server is more secure and less likely to be stolen. There is a downside to storing session information on the server, which takes up a lot of server resources, but now that the server has developed, it is more than enough to store some session information.

Use cookies and Sessions together: There are some very mature solutions for the use of cookies and sessions. There are two types of storage

  • Stored on the server: a session_id is stored in a cookie, and the specific data is stored in the session. If a user has logged in, the server stores a session_ID in the cookie and carries the session_ID in the next request. The server obtains session data from the sesson database based on the session_id. You can find out who the user is and what status information you saved. The technical term for this is calledserver side session.
  • The session data is encrypted and stored in cookies. The technical term for this is calledclient side session. Flask uses this method, but there are other alternatives.


The use of cookies

In Flask, a Response object is created using the make_response() function

Details of the set_cookie() method parameters of the Response object

def set_cookie(
        self,
        key,
        value="",
        max_age=None,	
        expires=None,
        path="/",
        domain=None,
        secure=False,
        httponly=False,
        samesite=None.) :
Copy the code

Common Parameters

  • keyThe keys of the cookie
  • valueThe value of the cookie
  • max_ageSet how long the cookie is stored in seconds. The default is one browser session. Close the browser and the cookie is gone.
  • expiresSet the cookie expiration date, which must be adatetimeObject type orUNIXThe time stamp
  • pathLimit cookie to a given path, by default it will belong to the entire domain name


If both max_age and Expires are set, the max_age parameter takes effect. If the expiration time is not set, the default is the end of the browsing session, which expires when the browser is closed (the browser is closed, not the page is closed)


Cookie setting and obtaining

from flask import Flask, make_response, request

app = Flask(__name__)


# set the Cookie
@app.route("/set_cookie")
def set_cookie() :
    resp = make_response('success')

    resp.set_cookie("name"."hui")
    resp.set_cookie("age"."21")

    return resp

# get Cookie
@app.route("/get_cookie")
def get_cookie() :
    name = request.cookies.get("name")
    age = request.cookies.get("age")

    resp = f"name={name}, age={age}"
    return resp


if __name__ == "__main__":
    app.run()
Copy the code


Use the make_response() function to create the Response Response object, and then use the set_cookie() method to set the cookie data

To get a Cookie, we use request.cookies. Get ()



The browser will automatically carry Cookie information on the next request. So get cookie information from request.cookies

View the Cookie expiration time


Cookie Sets the expiration time

from datetime import datetime, timedelta
from flask import Flask, make_response, request

app = Flask(__name__)


@app.route("/set_expires")
def set_cookie_expires() :
    resp = make_response("Set cookie expiration time")

    # Set to expire after 1 minute
    resp.set_cookie("sex"."male", max_age=60)

    # Set to expire after one day
    expires_date = datetime.now() + timedelta(days=1, hours=-8)
    resp.set_cookie("city"."GanZhou", expires=expires_date)

    return resp
Copy the code


If expires is used, the browser will default to Greenwich Mean time, automatically adding 8 hours to the set time, so we need to subtract 8 hours from the set expiration to mark our expectations.

A dateTime object cannot be added or subtracted from the time interval using timeDelta




Delete the Cookie

from flask import Flask, make_response

app = Flask(__name__)


@app.route("/del_cookie")
def del_cookie() :
    resp = make_response("del cookie")
    resp.delete_cookie("name")
    return resp
Copy the code

By deleting the cookie, it sets the expiration to max_age=0, expires=0

Take a look at Flask’s source code

    def delete_cookie(self, key, path="/", domain=None) :
        """Delete a cookie. Fails silently if key doesn't exist. :param key: the key (name) of the cookie to be deleted. :param path: if the cookie that should be deleted was limited to a path, the path has to be defined here. :param domain: if the cookie that should be deleted was limited to a domain, that domain has to be defined here. """
        self.set_cookie(key, expires=0, max_age=0, path=path, domain=domain)
Copy the code


The use of the Session

Session setting and obtaining

""" Author: Hui Desc: {Flask session} """
from flask import Flask, session

app = Flask(__name__)
app.config["SECRET_KEY"] = "it hui"


Flask stores sessions in cookies by default
@app.route("/index")
def index() :
    name = session.get("name")
    return "hello {}".format(name)


@app.route("/login")
def login() :
    session["name"] = "hui"
    return "set session name"


if __name__ == "__main__":
    app.run()
Copy the code


Remember to add the key configuration when setting the session

app.SECRECT_KEY = "it hui"
Copy the code

If this parameter is not set, the following error is reported

RuntimeError: The session is unavailable because no secret key was set.  Set the secret_key on the application to something unique and secret.
Copy the code


To test the above program, first access 127.0.0.1:5000/index


Then access 127.0.0.1:5000/login to set the session


Then go to 127.0.0.1:5000/index again


Flask stores sessions in cookies by default

Select * from hui session where name is set to view Cookie information

It’s just that the session information is encrypted, because the SECRET_KEY information is used to encrypt the session information, so the secret t_key is set when you set the session. Flask’s session information is stored in local cookies and can be tampered with. To ensure security, Flask considers this invalid session information once it is modified.


Session Indicates the expiration time

Flask session expires in one month by default. If the session expiration time is enabled (session.permanent=True), the default expiration time is one month. Permanent_session_lifetime Flask configuration information is used to set the duration of a session

From Flask source code

#: This attribute can also be configured from the config with the
    #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
    #: ``timedelta(days=31)``
    permanent_session_lifetime = ConfigAttribute(
        "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta
    )
Copy the code

Set the expiration time using a timeDelta object

Set session.permanent = True


""" Author: Hui Desc: {Flask session} """
from datetime import timedelta
from flask import Flask, session

app = Flask(__name__)
app.config["SECRET_KEY"] = "it hui"

Set session expiration time
app.permanent_session_lifetime = timedelta(seconds=60)


# Flask Stores sessions in cookies by default
@app.route("/index")
def index() :
    name = session.get("name")
    age = session.get("age")
    return f"name={name}, age={age}"


@app.route("/age")
def set_session() :
    session["age"] = 21
    return "set session age"


@app.route("/login")
def login() :
    session["name"] = "hui"
    session.permanent = True
    return "set session name"


if __name__ == "__main__":
    app.run()

Copy the code

Set the session expiration time to 1 minute

app.permanent_session_lifetime = timedelta(seconds=60)
Copy the code


Delete the session

@app.route("del_session")
def del_session() :
    session.pop("name")
    # session.clear() # Delete all session information
    return "del session name"
Copy the code


The source code

The source code has been uploaded to Gitee HuiDBK/FlaskBasic – Code Cloud – Open Source China (gitee.com), welcome to visit.

✍ code word is not easy, still hope you heroes support ❤️.


The public,

Create folder X

It took nature tens of billions of years to create our real world, and programmers hundreds of years to create a completely different virtual world. We hammer out bricks with keyboards and build everything with brains. People see 1000 as the authority, we do the opposite and defend 1024. We are not keyboard heroes, we are just extraordinary builders of the ordinary world.