Cookies and session s in python Django

Catalog

Cookie

1.1 Get Cookie

request.COOKIES["key"]
request.get_signed_cookie(key,default=RAISE_ERROR, salt='', max_age=None)
"""
Parameters:
        default: default value
           Salt: Encrypted salt
        max_age: Background control expiration time
"""

1.2 Setting Cookie

rep = HttpRespanse(...) or rep = render(reques,...)
rep.set_cookie(key,value,...)
rep.set_signed_cookie(key,value,salt='encrypted salt',...)
"""
Parameters:
        Key, key
        Value=', value
        max_age=None, timeout
        expires=None, time-out (IE required expires, so set it if hasn't been already.)
        Path='/', the path that Cookie takes effect, / represents the root path, and in particular, the cookie that follows the path can be accessed by any url's page.
        Domain = None, Cookie's valid domain name
        Secure = False, HTTPS transport
        httponly=False can only be transmitted by http protocol and can not be retrieved by JavaScript (not absolutely, the underlying package can be retrieved or overwritten)
"""

Because cookies are stored on client computers, JavaScript and jquery can also manipulate cookies.

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

Session

Session is supported by default in Django, which provides five types of Session internally for developers to use:

  • Database (default)
  • cache
  • file
  • Cache + Database
  • Encrypted cookie

1. Database Session

Django Default support Session,And the default is Session Data is stored in a database, that is: django_session In the table.
 
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 Yes. 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. Caching 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. Document 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

Database for persistence and cache for efficiency
 
a. 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

For more information: Crash here and Crash here

Extension: Session user authentication

def login(func):
    def wrap(request, *args, **kwargs):
        # If not logged in, jump to the specified page
        if request.path == '/test/':
            return redirect('http://www.baidu.com')
        return func(request, *args, **kwargs)
    return wrap

Tags: Python Session Database Django Javascript

Posted on Thu, 10 Oct 2019 01:58:34 -0700 by Gappa