session and cookie,django Middleware

Posted by toledojimenez on Mon, 19 Aug 2019 13:44:50 +0200

0819 self-summary

session and cookie

1.django sets session

request.session['name'] = username
request.session['age'] = 13
 A session ID of key: {"name":'username','age': 12} is automatically generated and encrypted in the latter part of django.
    

2. Get session

request.session.get('name')

3. Five session settings in Django

1. Database session

a. To configure settings.py
 
    SESSION_ENGINE = 'django.contrib.sessions.backends.db'   # Engine (default)
     
    SESSION_COOKIE_NAME = "sessionid"  # Session cookie s are saved on browsers as key, i.e. session ID = random string (default)
    SESSION_COOKIE_PATH = "/"   # Session cookie saved path (default)
    SESSION_COOKIE_DOMAIN = None    # Session cookie saved domain name (default)
    SESSION_COOKIE_SECURE = False    # Whether Https transfers cookie s (default)
    SESSION_COOKIE_HTTPONLY = True   # Whether Session cookie s only support http transport (default)
    SESSION_COOKIE_AGE = 1209600  # Session cookie expiration date (2 weeks) (default)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False  # Whether to close the browser to expire Session (default)
    SESSION_SAVE_EVERY_REQUEST = False  # Whether to save Session for each request, after default modification (default)
 
 
 
b. Use
 
    def index(request):
        # Get, Set, and Delete Data in Session
        request.session['k1']
        request.session.get('k1',None)
        request.session['k1'] = 123
        request.session.setdefault('k1',123) # Existence is not set
        del request.session['k1']
 
        # All key, value, key-value pairs
        request.session.keys()
        request.session.values()
        request.session.items()
        request.session.iterkeys()
        request.session.itervalues()
        request.session.iteritems()
 
 
        # Random string of user session
        request.session.session_key
 
        # Delete all data whose Session expiration date is less than the current date
        request.session.clear_expired()
 
        # Check whether the random string of user session is in the database
        request.session.exists("session_key")
 
        # Delete all Session data for the current user
        request.session.delete("session_key")
 
        request.session.set_expiry(value)
            * If value It's an integer. session It will fail in a few seconds.
            * If value It's a datatime or timedelta,session It will fail after that time.
            * If value It's 0.,User Closes Browser session It will fail.
            * If value yes None,session Will depend on the overall situation session Failure strategy.

2. Cache session

a.To configure settings.py
 
    SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # engine
    SESSION_CACHE_ALIAS = 'default' # The cache alias used (default memory cache, or memcache), where the alias depends on the cache settings
 
 
    SESSION_COOKIE_NAME = "sessionid"  # Session cookie s are saved on browsers as key s, i.e. session ID = random strings
    SESSION_COOKIE_PATH = "/"  # The path of cookie preservation for Session
    SESSION_COOKIE_DOMAIN = None      # Session cookie saved domain name
    SESSION_COOKIE_SECURE = False     # Whether or not Https transfers cookie s
    SESSION_COOKIE_HTTPONLY = True    # Whether Session cookie s only support http transport
    SESSION_COOKIE_AGE = 1209600      # Session cookie expiration date (2 weeks)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False     # Whether to close the browser to expire Session
    SESSION_SAVE_EVERY_REQUEST = False      # Whether Session is saved for each request, after default modification
 
 
 
b. Use
 
    //Ditto

3. File session

a. To configure settings.py
 
    SESSION_ENGINE = 'django.contrib.sessions.backends.file'    # engine
    SESSION_FILE_PATH = None  # Cache file path if None,Then use tempfile Module Gets a Temporary Address tempfile.gettempdir()                                                            # For example: / var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/T
 
 
    SESSION_COOKIE_NAME = "sessionid"   # Session cookie s are saved on browsers as key s, i.e. session ID = random strings
    SESSION_COOKIE_PATH = "/"   # The path of cookie preservation for Session
    SESSION_COOKIE_DOMAIN = None   # Session cookie saved domain name
    SESSION_COOKIE_SECURE = False    # Whether or not Https transfers cookie s
    SESSION_COOKIE_HTTPONLY = True     # Whether Session cookie s only support http transport
    SESSION_COOKIE_AGE = 1209600       # Session cookie expiration date (2 weeks)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False   # Whether to close the browser to expire Session
    SESSION_SAVE_EVERY_REQUEST = False   # Whether Session is saved for each request, after default modification
 
b. Use
 
    //Ditto

4. Caching + Database Session

a. To configure settings.py
 
    SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'        # engine
 
b. Use
 
    //Ditto

5. Encrypted cookie session

a. To configure settings.py
     
    SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies'   # engine
 
b. Use
 
    //Ditto

4. The relationship between session and cookie

1,cookie:

In a website, http requests are stateless. That is to say, even after the first connection to the server and the successful login, the second request server still can not know which user the current request is. Cookie is to solve this problem. After the first login, the server returns some cookies to the browser, and then the browser saves them locally. When the user sends the second request, the cookie data stored in the last request will be automatically carried to the server. The server passes through Liuzhou. The data carried by the viewer can tell which user is currently. Cookies store limited amount of data, different browsers have different storage sizes, but generally no more than 4KB. So cookies can only store a small amount of data.

2,session:

Sessions and cookies work a little bit like each other to store user-related information. The difference is that cookies are stored in local browsers, while sessions are stored in servers. The data stored in the server will be more secure and not easy to be stolen. However, there are some drawbacks of storage in the server, that is, it will occupy the resources of the server, but now the server has developed so far, some session information is more than enough.

3. The relationship between the two transmission

1. The first request from the client, the server will send the login page to the client.

2. After the customer requests the second time and submits the username and password, the server will write back a cookie value to the client.

3. If we set session, we will write back a {session id:'lr3gmj3vpt0ytf7locqnb21p0cg63iek'} to the client, which will be saved in the client.

4. The server saves the customer's privacy information in the server's database, that is session, which is stored in the database. By default, session is stored in the django_session table: {"dsjnalndjskanjdksa": {"name":'jojo','age': 12,'addr':'dsabdsa'}, which is stored in the form of session value: user information.

5. We can understand that the value of cookie is the key of session. When we make a request to the server again, the server compares the information through session id, and then returns the user information.

def login(request):
    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        username = request.POST.get('username')
        pwd = request.POST.get('pwd')

        if username == 'jojo' and pwd == '123':
            # Setting cookie s
            obj = redirect('/test/')
            obj.set_cookie('k1', 'abd')
            ### Write back a cookie value to the client
            '''
                1. Write back one to the client {sessionid : 'lr3gmj3vpt0ytf7locqnb21p0cg63iek'}
                2. Keep the customer's privacy information in the server-side database, that is to say session Stored in the database
                    //Default in django_session table
                    {"dsjnalndjskanjdksa" : {"name":'jojo', 'age':12, 'addr':'dsabdsa'}}
            '''
            # Setting session
            request.session['name'] = username
            request.session['age'] = 13
            
            # Get session
            request.session.get('name')
            
            return redirect('/test/')
        else:
            return render(request, 'login.html')

II. Middleware

General schematic diagram

Self-customized Middleware

Middleware can define five methods: process_request and process_response.

  • process_request(self,request)
  • process_view(self, request, view_func, view_args, view_kwargs)
  • process_response(self, request, response)

The return value of the above method can be None or an HttpResponse object. If it is None, it will continue to execute backwards according to the rules defined by django. If it is an HttpResponse object, it will be returned directly to the user.

process_request

The process_request has one parameter, request, which is the same as the request in the view function (a series of operations can be performed on the request object before the route is given to Django).

Because the request object is the same, we can perform a series of operations on the request object, including request. Variable name = variable value, so that we can get the values we set in the middleware in the same way in subsequent view functions.

Its return value can be either None or HttpResponse object. If the return value is None, follow the normal process and leave it to the next middleware. If it is a HttpResponse object, Django will not execute the view function, but return the corresponding object to the browser.

process_response

The process_response method in multiple middleware is executed in reverse order according to the registration order in MIDDLEWARE. That is to say, the process_request method of the first middleware is executed first, and its process_response method is executed last, and the process_request method of the last middleware is executed last, and its process_response is executed first. The SE method is the first to execute.

process_view

process_view(self, request, view_func, view_args, view_kwargs)

The method has four parameters

  • request is the HttpRequest object.
  • view_func is the view function that Django will use soon. (It's the actual function object, not the name of the function as a string.)
  • view_args is a list of location parameters passed to the view.
  • View_kwargs is a dictionary of keyword parameters passed to the view. view_args and view_kwargs do not contain the first view parameter (request).

Django calls the process_view method before calling the view function.

It should return None or an HttpResponse object. If None is returned, Django will continue to process the request, execute the process_view method of any other middleware, and then execute the corresponding view. If it returns an HttpResponse object, it will not execute Django's view function, but will directly turn around in the middleware, rewind and execute process_response methods, and finally return to the browser.

Middleware execution process

After the request arrives at the middleware, the process_request method of each registered middleware is executed in positive order, and the value returned by the process_request method is None. If the value returned by the process_request method is the HttpResponse object, the process_response method of the current corresponding middleware is executed instead of the later process_request method. Method (note that not all process_response methods are turned around), returning the HttpResponse object to the browser. That is, if six middleware are registered in MIDDLEWARE and the third middleware returns an HttpResponse object during execution, then the process_request and process_response methods of middleware 4, 5 and 6 are not executed, and the process_response methods of middleware 3, 2, 1 are executed sequentially.

After the process_request method is executed, the routing is matched and the view function to be executed is found. First, the view function is not executed. First, the process_view method in the middleware is executed. Then the process_view method returns None and continues to execute in sequence. After all the process_view methods are executed, the view function is executed. If the process_view method of middleware 3 returns the HttpResponse object, the process_view and view functions of 4,5,6 are not executed, and they are executed in reverse order from the process_response method of middleware 6, which is the last middleware.

Topics: Python Session Django Database less