django7-cookie与session

1. There are no state services and state services

  Examples of the data storage service client, then this is a stateful service

  Service instance does not store client data, so that other client-side data cache memory, which is stateless service, http is stateless

 

2. What is a cookie

  Server stored in the client's key information, each client access will carry cookie, cookie server to operate judge

 

3. Log function package cookie

  With the post request to see the response object encapsulates a k: v, jump to get this value will presslist

def presslist(request):
    ck = request.COOKIES.get('user')
    print(ck)
    msg_all = models.presslist.objects.all()
    return render(request, 'cbs.html', {'msg': msg_all})

class tlogin(View):

def get(self, request):
if request.COOKIES.get('user'):
return redirect(reverse('presslist'))
return render(request, 'login.html')

def post(self, request):
user = request.POST.get('user')
password = request.POST.get('password')
print(user, password)
if models.Author.objects.filter(name=user, password=password):
ret = redirect(reverse('presslist'))
# 在response对象中封装cookie ,下次客户端会带过来
ret.set_cookie('user', 'auth')
return ret

return render(request, 'login.html')

  Decorator: Imagine if all views are required to have the client uses the cookie, then we need to judge each view plus cookie, so we use a decorator to complete, you can use the back of the global function processing middleware

def wrap1(func):
    def inner(request, *args, **kwargs):
        if request.COOKIES.get('user'):
            ret = func(request, *args, **kwargs)
            return ret
        return redirect(reverse('tlogin'))

    return inner

@wrap1
def presslist
...
@wrap1
def pressadd
...
@wrap1
def pressedit
...
@wrap1
def pressdel

def tlogin()
...

  Retain user search: Users can browse our display interface, but when we need to use the new login, login if you can jump to the new page is consistent with experience, so we have to modify the login Jump

# # If not logged in, login page will jump when carrying a parameter, the user wants to access, but the address you want to register 
DEF wrap1 (FUNC):
     DEF Inner (Request, * args, ** kwargs):
         IF Request.Cookies. GET ( ' the user ' ): 
            RET = FUNC (Request, * args, ** kwargs)
             return RET
         # keep the user record, spliced to address 
        nowurl = request.path_info
         return redirect (Reverse ( ' tlogin ' ) + ' the Next =? } { ' .format (nowurl)) 

    return Inner 

## If the successful landing, this time requiring jumps to address user wants to access, but need to log in, taken out in the url, if there is no default is to presslist 
class tlogin (View): 

    DEF GET (Self, Request):
         IF Request. COOKIES.get ( ' User ' ):
             return the redirect (Reverse ( ' presslist ' ))
         return the render (Request, ' the login.html ' ) 

    DEF POST (Self, Request): 
        User = request.POST.get ( ' User ' ) 
        password = request.POST.get ( ' password ' )
         IFmodels.Author.objects.filter (= User name, password = password): 
            URL = Reverse ( ' presslist ' ) 
            Next = request.GET.get ( ' Next ' )
             IF Next: 
                URL = Next 
            RET = the redirect (URL)
             # in response encapsulated object cookie, the client next brought over 
            ret.set_cookie ( ' User ' , ' the auth ' )
             return RET 

        return the render (Request, 'login.html')

  use of cookie in django

    1. Set the cookie

      1) Get the object httpresponse ret, generally acquires the login function

      2)ret.set_cookie(key,value) ,设置cookie

      3) Use decorators to help each function to verify the existence of cookie request.COOKIES.get (key)

      4) set the cookie timeout ret.set_cookie (key, value, max_age = 10), 10 seconds after setting the timeout

      5) is provided only for a url cookie, ret.set_cookie (key, value, path = '/ app01 / addpress')

    2. Remove cookie (logout function)

      ret.delete_cookie ( 'authck') to delete a key value of the cookie

# Front end of the logout button 

# # 
# the urls.py 
URL (R & lt ' Zimbabwe Logout / ' , views.logout),
 # the views.py 
DEF Zimbabwe Logout (Request): 
    RET = the redirect ( ' / app01 / Login2 / ' ) 
    ret.delete_cookie ( ' authck is ' )
     return RET

4. What is the session

  session cookie and key-value pairs are similar, but the session is stored in the server for security, the sessionid cookie to the client into the store, every time a client access server, server to determine the user according to stored cookie sessionid

  django db used in a table storing session information table django_session

    session_key field stores the client sessionid

    session_data stored encrypted client data

    expire_date store this recording session expiration time (by setting change)

The session login function package

  The only difference is that with the cookie, the session on the subject of the request, the cookie on the response object, even if the request object into the session, the client will receive a cookie stored sessionid

## decorator modify, obtain session request from the 
DEF wrap1 (FUNC): 
    DEF Inner (request, * args, ** kwargs): 
        # IF . Request.Cookies GET ( ' User ' ):
         IF makes request.session. GET ( ' the auth ' ): 
            RET = FUNC (Request, * args, ** kwargs)
             return RET 
        # keep the user records, to the address spliced 
        nowurl = request.path_info
         return the redirect (Reverse ( ' tlogin ' ) + ' Next} = {?' .Format (nowurl)) 

    return Inner 

## Log function uses the request object created in a dictionary 
class tlogin (View): 

    DEF GET (Self, request):
         IF Request.Cookies. GET ( ' the User ' ):
             return redirect (Reverse ( ' presslist ' ))
         return the render (request, ' login.html ' ) 

    # Jump in post to deal with the request, because only a successful login to the user record jump 
    DEF post (Self, request): 
        the user = request. POST. GET ( ' the User ') 
        Password = of request.POST. GET ( ' password ' )
         IF models.Author.objects.filter (= User name, password = password): 
            URL = Reverse ( ' presslist ' ) 
            Next . = `` Request.GET`` GET ( ' Next ' )
             IF next: 
                URL = next 
            RET = the redirect (URL) 
            # encapsulated object in response cookie, will take over the next client 
            # ret.set_cookie ( ' User', 'auth')
            request.session['auth'] = 'user'
            return ret

        return render(request, 'login.html')

   django session using the same operation Dictionary

    request.session.get (key) # get into session

    request.session.set_expiry (time) # set the session timeout

    request.session.flush () # delete information about the browser and the server's answer, and do the same cookie cancellation of use

  View session and configuration session 

    from django.conf import global_settings # Click global_settings can see the changes

1.session storage 

  database session (default)     SESSION_ENGINE
= ' django.contrib.sessions.backends.db '   Cache memory session (Redis memcache)     SESSION_ENGINE = ' django.contrib.sessions.backends.cache ' # engine     SESSION_CACHE_ALIAS = ' default ' # use an alias cache (cache memory by default, may be memcache), provided by the alias cache dependency   buffer + database SESSION_ENGINE = ' django.contrib.sessions.backends.cached_db ' 2 the .session other universal set SESSION_COOKIE_NAME = " SessionID " #Key Session of the cookie stored in the browser, namely: sessionid = random string (the default) SESSION_COOKIE_PATH = " / " # saved Session cookie path (default) SESSION_COOKIE_DOMAIN = None # saved Session of cookie domain (default) SESSION_COOKIE_SECURE = False # whether Https transfer cookie (default) SESSION_COOKIE_HTTPONLY = True # whether the Session cookie only supports http transmission (default) SESSION_COOKIE_AGE = 1209600 # Session of cookie expiration date (two weeks) (default) SESSION_EXPIRE_AT_BROWSER_CLOSE is = False # if you close your browser making Session expired (default) = False SESSION_SAVE_EVERY_REQUEST # whether each request Save Session, was saved after modifying default (default)

 

 

  

Guess you like

Origin www.cnblogs.com/quguanwen/p/11419470.html