In the past few days, I have learned session and cookie systematically. When I first learned Django, I didn’t understand these two concepts very well. Today, I feel that I have understood them, so I plan to write them down.

First of all, let’s talk about cookies. It can be understood that the existence of cookies leads to the existence of sessions. There can be no session, but there cannot be no cookies.

Cookies in my own words, is the browser to the server to see an id, id card, this id card is written with the client’s information, such as a user name what, such as when the client sends a request to the server, at the same time will this id card to the server, the server will know who you are, You can do something later. Of course, if you visit the server for the first time, you will not have the ID card cookie. At this time, when you send a request, the server finds that there is no cookie in your head, knows that it is your first visit, and will send you an ID card, that is, configure a cookie for you, and then return it together with the data you requested. It goes to your client, the browser, and when your browser opens the page, it also saves the cookie in your browser. Of course, if you have multiple browsers on your computer, the cookies in those browsers are not connected.

You might say, well, how can the server see your ID card and be sure that there’s nothing wrong with it? Maybe you faked it yourself, right, so the session comes into play at this point. When you visit the server for the first time, the server will add a sessionid to your ID card and store some information in the server memory, which is used to mark the sessionid.

If you’ve ever been to a gym, you know that when you go, you hand your gym card to the front desk, who swipes it, and you’re ready to go. It’s kind of like cookies and sessions, you go to the server, you have a cookie with a session ID in it, the server gets the session ID, goes into the database and looks for your information, and then returns the page, so it’s pretty straightforward.

Djangos session code and cookie code

1. Set the cookie

Cookies can be set using the set_cookie method in the HttpResponse object. The expiration time is in seconds, because you’re setting the cookie in the response header, so the object is an HttpResponse.

Httpresponse.set_cookie (cookie name, value=cookie value, max_age=cookie validity period)Copy the code
def cookie(request):
    response = HttpResponse('ok')
    response.set_cookie('message1'.'python1')  # temporary cookies
    response.set_cookie('message2'.'python2', max_age=3600)  Valid for one hour
    return response
Copy the code

2 read the Cookie

The cookie value carried by this request can be read through the COOKIES property of the HttpResponse object. Request.COOKIES is of dictionary type. Both cookies and sessions use dictionaries to store data. Since the cookie is stored in the request header, the cookie data can be retrieved in the request.

def cookie(request):
    cookie1 = request.COOKIES.get('message1')
    print(cookie1)
    return HttpResponse('OK')
Copy the code

3 deleting cookies

This can be done through the delete_cookie method in the HttpResponse object. The delete_cookie method can sometimes be used to delete information that has been modified or deleted by the user.

response.delete_cookie('message2')
Copy the code

That’s pretty much it for cookies, and then for sessions:

1 Storage Mode

Session can be stored in a database or in memory, so of course you can use mysql or Redis to store data. In settings.py, you can set how session data is stored, whether in the database, local cache, etc.

1.1 database

Storage in the database, the following Settings can be written or not written, this is the default storage.

SESSION_ENGINE='django.contrib.sessions.backends.db'
Copy the code

If the Session application is stored in the database, you need to install the Session application in INSTALLED_APPS. Add a line of ‘django.contrib.sessions’ and you’ll be ok

The session in the database contains three important data: key, value, and expiration time.

1.2 Local Cache

If the data is stored in memory, it is fast to read, but if the data is lost, it will be cool.

SESSION_ENGINE='django.contrib.sessions.backends.cache'
Copy the code

1.3 Mixed Storage

First fetch from memory, if not from database

2 the Session operation

Of course, you can also set the database to mysql and Redis which are available online. Next, write a few important session operations:

Much like cookies, sessions are written to key-value pairs, and fetched in the same way

request.session['key'] = value request. Session. Get ('key', default)Copy the code

Clear all sessions and delete the value portion from the store.

request.session.clear()
Copy the code

Clear session data: Deletes the entire session data from the storage.

request.session.flush()
Copy the code

Deletes specified keys and values from the session. Deletes only one key and its value from the store.

del request.session['key']
Copy the code

Set the session validity period

request.session.set_expiry(value)
Copy the code

Almost the basic knowledge of cookie and session is almost summarized. In fact, the understanding process is a process of taking gym card, and the code part is quite understandable, nothing more than adding or deleting data in the request header and corresponding header, and are stored in the form of key-value pairs, so it is not difficult.

Day arch a pawn, work does not donate tang.

After the