Cookie s and sessions in Django framework

Posted by SOL-ion on Thu, 18 Nov 2021 11:46:32 +0100

preface

Over the past few years, I have been struggling in the it industry. Along the way, many have summarized some high-frequency interviews in the python industry. I see most of the new blood in the industry, and I still have all kinds of difficult questions for the answers to all kinds of interview questions or collection

Therefore, I developed an interview dictionary myself, hoping to help everyone, and also hope that more Python newcomers can really join the industry, so that Python fire does not just stay in advertising.

Wechat applet search: Python interview dictionary

Or follow the original personal blog: https://lienze.tech

You can also focus on WeChat official account and send all kinds of interesting technical articles at random: Python programming learning.

Cookie

In django's code, we can use some classes that provide Response, such as the built-in set of HttpResponse, redirect and other instances_ Cookie function to set cookies in django project

set_cookie(key, value='', max_age=None, expires=None, path='/',domain=None, secure=False, httponly=False)
'''
key: Cookie of key Value, which will be passed in the future key Get the corresponding set value Cookie. 
value='': corresponding Cookie of key Value value,such as: set_cookie(key='value',value='shuai')
max_age=None: Cookie Effective time, in seconds, if Cookie If the value only lasts for the session duration of the client browser, this value should be None. When this value exists, expires Will be calculated.
expires=None: Cookie The specific expiration date is a datetime.datetime Object, if the value exists max_age Will also be calculated

path='/': Specify which url Can access Cookie,default/For all.
domain=None: When we need to set as a cross domain Cookie Value, you can use this parameter, such as: domain='.test.com',So this Cookie Values can be www.test.com,bbs.test.com And other domains with the same primary domain name. Otherwise Cookie It is only read by its domain set. by None When, it represents the global effect under the current domain name.
secure=False: https Encrypted transmission settings when used https This value needs to be set for protocol. Similarly, if this value is set to True,If not https This message will not be sent when connected Cookie Value.
httponly=False: HTTPOnly Is included in HTTP In response header Set-Cookie A tag in. For one bool Value when set to True On behalf of blocked clients Javascript visit Cookie. This is a way to reduce client script access protection Cookie Effective approach to data risk
'''
import datetime
current_time = datetime.datetime.now() # current time 
expires_time = current_time + datetime.timedelta(seconds=10) # Push back ten seconds
set_cookie('key','value',expires=expires_time) #Set Cookie and corresponding timeout

Set COOKIE

Realize the setting of COOKIE

from django.shortcuts import render,HttpResponse

# Create your views here.
def set_cookie(request):
    # Set the COOKIE value in the HTTP response section
    cookie_reponse = HttpResponse('This is about cookie Test of')
    cookie_reponse.set_cookie('test','hello cookie')
    return cookie_reponse

The above view function returns an HttpResponse object and integrates the setting of COOKIE value in this object. Set the key value to test and the value to hello cookie

Get COOKIE

Let's simply implement the acquisition of COOKIE

def get_cookie(request):
    # Get the cookie value from the cookie attribute in the request attribute
    cookie_data = request.COOKIES.get('test')
    return HttpResponse('Cookie Value is:%s' % cookie_data)

The Cookie value is stored in the COOKIES attribute in the request

And the result obtained by this attribute is similar to the dictionary in python, which can be obtained directly through the built-in function get

Delete COOKIE

Here, the COOKIE is deleted through the view function route

def delete_cookie(request):
    response = HttpResponseRedirect('/check_cookie/')
    response.delete_cookie('test')
    return response
delete_cookie(key, path='/', domain=None)

Delete the specified key and corresponding value in the Cookie. If the key value does not exist, no exception will be thrown.

Because of the way cookies work, path and domain should be the same as set_ The value used for the Cookie is the same, otherwise the Cookie value will not be deleted

Delete the corresponding class through the response_ The Cookie method, which should have disappeared after the end of the session, has now been deleted directly. In the background, the value obtained through the Cookie dictionary in the Request is also None

Don't forget to get the dictionary. If you can't get the result, return None

However, there is another problem. The Cookie value stored in the user's browser is plaintext, which has great security risks. django also provides a way to store and obtain the Cookie value supporting visa

Tamper proof COOKIE

By set_ signed_ The COOKIE function sets the COOKIE value holding the signature to prevent the user from modifying it on the client

Remember that this function does not encrypt the COOKIE value

HttpResonse.set_signed_cookie(key, value, salt='', max_age=None,
expires=None, path='/', domain=None, secure=None, httponly=True)
# Add a signature for the cookie value, and the other parameters are the same as set_ Same cookie
Request.get_signed_cookie(key, salt='', max_age=None)
# Obtain the signed 'Cookie' value through salt salt value from the user request

The salt value here must be the same as the salt value used in previous storage to parse the correct result.

Also note that if the corresponding key value does not exist, a KeyError exception will be thrown, so remember to catch the exception to determine whether it contains a Cookie value

def check_salt_cookie(request):
    try:
        salt_cookie = request.get_signed_cookie(key='salt_cookie',salt='nice')
    except KeyError: #The Cookie for the key value could not be obtained
        response = HttpResponse('Setting up a salt Cookie value')
        response.set_signed_cookie(key='salt_cookie',salt='nice',value='salt_cookie')
        return response
    else: #The corresponding key value is obtained and displayed in the new HttpResonse
        return HttpResponse('Obtained salt Cookie value:%s' % salt_cookie)

During the first visit, the Cookie value has not been added, so we will throw a KeyError exception when getting it

At this time, you can catch exceptions and set cookies;

When refreshing again, because the Cookie value has been given here, no exception will be thrown, and the obtained salted Cookie will be displayed on the page

Session

Although after having cookies, we save some information in the client browser, which can maintain the user's state when accessing the site, there are also certain security risks, such as the Cookie value is exposed, the Cookie value is tampered with by others, and so on. We will change to a more sound way, that is, the next Session.

Session in the network, also known as session control, referred to as session. It is used to store the information and configuration properties required by users when accessing the site. When users jump in our Web service, the data stored in the session will not be lost and can survive throughout the session.

In django, the default session is stored in the session table in the database. The default validity period is two weeks.

session creation process

  1. The client accesses the server, which returns a unique sessionid for each client, such as xxx.
  2. The client needs to maintain some state, such as maintaining login. Then the server will construct a {sessionid: xxx} dictionary data like this, add it to the Cookie and send it to the user. Note that at this time, it is just a random string, and the content returned to the client will not contain the actual data as before.
  3. The server takes the xxx string returned to the client as the key value in the background, and the corresponding server data to be saved is a new dictionary, which is stored on the server, for example: {xxx: {ID: 1}}

After that, some client data access is obtained by acquiring the sessionid in Cookie in the HttpRequest request initiated by the client to the server, and then retrieving the Session data stored by the client from the Session data of the server with the sessionid.

  • Note: Supplementary Note: the Session data stored in the database by default is encoded through Base64. We can decode the original data through b64decode() under the base64 module of Python

After the whole process: the client browser actually stores only a random string (xxx) identifying the session

In the server, the random string (xxx:value) is used for real storage

Session must be used under Settings configuration

INSTALLED_APPS = (
	...
    'django.contrib.sessions',
    ...
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
	...
)

When SessionMiddleware in settings.py is activated

In the parameter request of the view function, the httprequest request object received from the client will contain a session attribute

This attribute is similar to the Cookie discussed earlier. It is a dictionary like object. First, it supports the following common dictionary built-in attributes

Get Session

session_data = request.session.get(Key)
session_data = request.session[Key]

Get the corresponding value in Session. If the Key value does not exist during get, no exception will be thrown and None will be returned

The second method is obtained directly through the get method. If the Key value does not exist, KeyErro is triggered

Delete Session

del request.seesion[Key]
# Delete the corresponding session. When the Key value does not exist, a KeyError is raised
request.session.clear()
# Clear all data in the Session. Here, the client will also retain the sessionid;
# But the data corresponding to the sessionid on the server is gone
request.session.flush()
# Directly delete the Seesion data of the current client. Not only does the data corresponding to the server sessionid disappear, but the client's' sessionid 'will also be deleted

Set validity period

request.session.set_expiry(value)
# Set the effective time of the Session
'''
value: Effective time.
	- When is an integer: Will be in value Expires in seconds
	- When 0: Expires after the user closes the browser.
  - by None Time: Use the global expiration setting. The default is two weeks and 14 days.
  - by datetime Time: Expires after this specified time
'''
request.session.get_expiry_age()
# Returns the number of seconds left before expiration
request.session.clear_expired()
# Clear expired Session sessions
  • session example
from django.shortcuts import render,HttpResponse
import datetime
def set_session(request):
    if request.session.get('test_id'):
        session_data = request.session.get('test_id')# session random string obtained by the user
        session_key = request.session.session_key # Gets the SessionID value in the client browser
        session_expire = request.session.get_expiry_age()
        now = datetime.datetime.now()
        expire_time = now + datetime.timedelta(seconds=session_expire)
        response = '<div>SessionID : %s</div>' % session_key + \
                   '<div>Session : %s</div>' % session_data + \
                   '<div>ExpireTime : %s</div>' % expire_time
        return HttpResponse(response)
    else:
        request.session['test_id'] = 'TEST'
        request.session.set_expiry(None)
		return HttpResponse('Set Session')

During the first visit, the user will take the else branch. At this time, there is no Session on the server and Cookie value on the client

Then we will set a session value through request.session[Key], which is TEST

When the user accesses for the second time, the set Session value and the sessionid stored in the client browser will be displayed

Write a view function to delete Session

def delete_session(request):
    if request.session.get('test_id'):
        del request.session['test_id']
        return HttpResponse('Session Deleted')
    else:
        return HttpResponse('There is nothing to delete at present session')

Here, gently use del request.session[Key] to delete a Session

If there is a corresponding test_ The Session value of ID is deleted, otherwise a string is returned

Session delete summary

The targeted deletion method of del is used, so that the entire client session will not be deleted

Using request.session.clear() only clears the data in the server session, but the sessionid will also be saved in the client Cookie, but the user data corresponding to the string corresponding to this value is empty

Using request.session.flush(), the sessionid saved in the client Cookie will be deleted first, and then all the user data saved by the server through the sessionid value will be deleted.

Topics: Python Django Back-end