Cookie, Session finishing supplement of Django framework

Browse the catalog

1. Cookies implemented by Django

1. Get cookies

request.COOKIES['key']
request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)
    #parameter:
        default: default value
           salt: encrypted salt
        max_age: background control expiration time  

2. Set cookies

rep = HttpResponse(...) 或 rep = render(request, ...) 或 rep = redirect()
 
rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='encrypted salt',...)   

parameter:

def set_cookie(self, key,                 键
             value='', value
             max_age=None, super long time
             expires=None, too long
             path='/', the path where the cookie takes effect,
                                         The browser will only pass the cookie back to the page with that path, which avoids the
                                         Cookies are passed to other applications on the site.
                                         / Represents the root path, special: the cookie of the root path can be accessed by any url page
             
                     domain=None, the domain name where the cookie takes effect
                                        
                                          You can use this parameter to construct a cross-site cookie.
                                          如, domain=".example.com"
                                          The constructed cookie is readable by the following sites:
                                          www.example.com 、 www2.example.com
                         and an.other.sub.domain.example.com.
                                          If this parameter is set to None, the cookie can only be read by the site that set it.

             secure=False, if set to True, the browser will pass the cookie back and forth via HTTPS.
             httponly=False can only be transmitted by the http protocol and cannot be obtained by JavaScript
                                         (Not absolute, the underlying packet capture can be obtained or overwritten)
          ): pass  

Since cookies are stored on the client's computer, JavaScript and jQuery can also manipulate cookies.

<script src='/static/js/jquery.cookie.js'>
 
</script> $.cookie("key", value,{ path: '/' }); 

3. Delete cookies

response.delete_cookie("cookie_key",path="/",domain=name)

The advantages of cookies stored on the client side
       :
           data exists on the client side, reducing the pressure on the server side and improving the performance of the website.
       Disadvantages:
           low security: it is easy to view or crack user session information on the client machine  

2. Session implemented by Django

1. Basic operation

1. Set the Sessions value
          request.session['session_name'] ="admin"
2. Get the Sessions value
          session_name = request.session["session_name"]
3. Delete the Sessions value
          del request.session["session_name"]
4. Check whether the session value is manipulated
          if "session_name" is request.session :
#Other operations

5、get(key, default=None)
 
fav_color = request.session.get('fav_color', 'red')
 
6、pop(key)
 
fav_color = request.session.pop('fav_color')
 
7、keys()
 
8、items()
 
9、setdefault()
 
10. flush() deletes the current session data and deletes the session cookies.
            This is used to ensure that previous session data cannot be accessed again by the user's browser
            For example, it is called in the django.contrib.auth.logout() function.
 
 
11 Random string for user session
        request.session.session_key
  
        # Delete all data whose session expiration date is less than the current date
        request.session.clear_expired()
  
        # Check if the random string of the user session is in the database
        request.session.exists("session_key")
  
        # Delete all session data of the current user
        request.session.delete("session_key")
  
        request.session.set_expiry(value)
            * If value is an integer, the session will expire after a few seconds.
            * If value is a datatime or timedelta, the session will expire after this time.
            * If the value is 0, the user closes the browser session will be invalid.
            * If the value is None, the session will rely on the global session invalidation policy.

2. Process analysis diagram

3. Examples

views:

def log_in(request):

    if request.method=="POST":
        username=request.POST['user']
        password=request.POST['pwd']

        user=UserInfo.objects.filter(username=username,password=password)

        if user:
             #Set the dictionary content inside the session 
            request.session[ ' is_login ' ]= ' true ' 
            request.session[ ' username ' ]= username

            #If the login is successful, redirect the url to the url in the background 
            return redirect( ' /backend/ ' )

    #Login is unsuccessful or stays on the login page for the first visit 
    return render(request, ' login.html ' )




def backend(request):
    print(request.session,"------cookie")
    print(request.COOKIES,'-------session')
    """
    Here, the value of is_login must be set to False by default with the get() method of reading the dictionary.
    When the user accesses the backend url, first try to obtain the url in the session corresponding to the browser
    The value of is_login. If the other party logs in successfully, is_login is already in the login
    The value is changed to True, otherwise the value is False
    """

    is_login =request.session.get( ' is_login ' ,False)
     #If true, it means that the user is logged in normally 
    if is_login: #Get
         the content of the dictionary and pass in the page file 
        cookie_content= request.COOKIES
        session_content=request.session

        username=request.session['username']

        return render(request,'backend.html',locals())
    else:
        """
        If the correct session is not carried when accessing,
        It is directly redirected to the url back to the login page
        """
        return redirect('/login/')



def log_out(request):
    """
    When returning directly through request.session['is_login'],
    If the value corresponding to is_login does not exist, it will cause a program exception. so
    Exception handling is required
    """ 
    try :
         #Delete the value corresponding to is_login del request.session [ ' is_login ' ]
        
        
        # OR---->request.session.flush() # Delete the corresponding row in the django-session table

    except KeyError:
         pass 
    #After clicking logout, redirect directly back to the login page 
    return redirect( ' /login/ ' )
View Code

template:

===================================login.html==================
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="/login/" method="post">
    <p>用户名: <input type="text" name="user"></p>
    <p>密码: <input type="password" name="pwd"></p>
    <p><input type="submit"></p>
</form>


</body>
</html>


===================================backend.html==================

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<h3>hello {{ username }}</h3>
<a href="/logout/">注销</a>

</body>
</html>
View Code

4. Related configuration of session storage

1. Database configuration (default)

Django supports Session by default, and the default is to store Session data in the database, namely: the django_session table.
  
a. Configure settings.py
  
    SESSION_ENGINE = 'django.contrib.sessions.backends.db' # engine (default)
      
    SESSION_COOKIE_NAME = "sessionid" # The key when the session's cookie is saved on the browser, namely: sessionid=random string (default)
    SESSION_COOKIE_PATH = "/" # Session cookie save path (default)
    SESSION_COOKIE_DOMAIN = None # The domain name where the session's cookie is saved (default)
    SESSION_COOKIE_SECURE = False # Whether Https transmits cookies (default)
    SESSION_COOKIE_HTTPONLY = True # Whether the session's cookie only supports http transmission (default)
    SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) (default)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to make the session expire (default)
    SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request, and save it after the default modification (default)

2. Cache configuration

a. Configure settings.py
  
    SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # 引擎
    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" # The key when the session's cookie is saved on the browser, namely: sessionid=random string
    SESSION_COOKIE_PATH = "/" # Path where session cookies are saved
    SESSION_COOKIE_DOMAIN = None # The domain name saved by the session's cookie
    SESSION_COOKIE_SECURE = False # Whether Https transmits cookies
    SESSION_COOKIE_HTTPONLY = True # Whether the session's cookie only supports http transmission
    SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to make the session expire
    SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request, and save it after the default modification  

3. File configuration

a. Configure settings.py
  
    SESSION_ENGINE = 'django.contrib.sessions.backends.file'    # 引擎
    SESSION_FILE_PATH = None # Cache file path, if None, use tempfile module to get a temporary address tempfile.gettempdir()        
    SESSION_COOKIE_NAME = "sessionid" # The key when the session's cookie is saved on the browser, namely: sessionid=random string
    SESSION_COOKIE_PATH = "/" # Path where session cookies are saved
    SESSION_COOKIE_DOMAIN = None # The domain name saved by the session's cookie
    SESSION_COOKIE_SECURE = False # Whether Https transmits cookies
    SESSION_COOKIE_HTTPONLY = True # Whether the session's cookie only supports http transmission
    SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks)
    SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to make the session expire
    SESSION_SAVE_EVERY_REQUEST = False # Whether to save the Session for each request, and save it after the default modification

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324937421&siteId=291194637