Seventeen .Django cookie application

Application of a .cookie

Introduction 1. cookie

In the program, session tracking is a very important thing. In theory, a user requests that all operations should belong to the same session, and another user requests all the operations should belong to another session, 
the two can not be mixed while the Web application is using the HTTP protocol for transferring data. HTTP protocol is stateless protocol. Once the data exchange is completed, the client and server-side connection will be closed again to exchange data need to establish a new connection.
This means that the server can not connect from a session on the track. To track the session, a mechanism must be introduced. Cookie is one such mechanism. It can compensate for the lack stateless HTTP protocol. Before Session appears, essentially all of the sites use to track Cookie session.
  About cookie, keep in mind several points:

     - 1 .cookie is encrypted key is stored in the user's browser to

     - 2 can be actively cleared (the browser interface, front-end, back-end).

     - 3. can be " forged "
 
    - 4. the purpose in privacy protection, prohibit cross-domain shared: that www.googole.com and www.baidu.com each cookie can not be shared, because the domain name corresponding Google Inc. and Baidu's server is different
设置cookie
def coo(request):
          if request.method=="POST":

                 print(request.COOKIES)
                 name=request.POST.get("usre")
                 pwd=request.POST.get("pwd")
                 if name=="aaaa" and pwd=="123":
                     ret=redirect("/myapp/index")
                     ret.set_cookie("lover","good")   # 设置 set_cookie 
                     return ret
          return render(request,"html_app/05cookie.html")

获取cookie
def index(request): if request.COOKIES.get("lover",None)=="good": name="aaaa" return render(request,"html_app/06index.html",{"aa":name}) else: return redirect("/myapp/cookie/")
cookie技术   带有过期时间

def coo(request): if request.method=="POST": print(request.COOKIES) name=request.POST.get("usre") pwd=request.POST.get("pwd") if name=="aaaa" and pwd=="123": ret=redirect("/myapp/index") ret.set_cookie("Lover " , " Good " ) # Set set_cookie # ret.set_cookie (" username ", {" 11 ":" 22 is "}, the max_age = 10) and expiration time set_cookie Set # ret.set_cookie ( " username " , { " . 11 " : " 22 is " }, the max_age = 10, datetime.datetime.utcnow expires = () + the datetime.timedelta (Days =. 3)) # set expiration set_cookie and return RET return the render (Request, " html_app / 05cookie.html " ) DEF index (Request): if request.COOKIES.get("username",None) name=request.COOKIES.get("username",None) return render(request,"html_app/06index.html",{"aa":name}) else: return redirect("/myapp/cookie/")
# views.py

def login(request):  # 登陆页面
    if request.mothod == 'POST':
        name = request.POST.get('user')
        pwd = request.POST.get('pwd')

        if name == 'yuan' and pwd == '123':

            ret = redirect('/index/')
            ret.set_cookie('key',' Value ' )     # after the successful landing, cookie assigned to a set of key-value pairs 
       # ret.set_cookie ( 'username', 'Yuan', max_age = 10, the Expires = datetime.datetime.utcnow () + datetime.timedelta (Days = 3)) 
        # max_age set cookie expiration time is 10 seconds, expires set the cookie expiration time was 3 days (the same for different browsers, you need to set both values at the same time, and is set to) 
            return RET 


DEF index (Request):
    # IF request.COOKIES.get ( 'key', None) : # determines whether the user has provided the key cookie 
  iF request.COOKIES.get ( ' key ' , None) == ' value ' :  # Get the cookie value, determines whether the key as the representative value, when not to None None taken place, so that no error 
    return the render (Request, ' index.html',locals())
  else:
    return redirect('/login/')
Tour to view the cookie method: cookie here by "Inspect Element" tour's -> " Network " > - " Cookies " see 

request.COOKIES: contains all the data sent to the user, this COOKIES is a dictionary, get the method has the following two 
acquisition cookis, obtaining cookies sent by a user request 
Request.Cookies [ ' username111 ' ] 
request.COOKIES.get (
' username111 ' ) disposed cookies, the server returns to the client, and write cookies Response = the render (Request, ' index.html ' ) Response = the redirect ( ' / index / ' )
# set a cookie, visit automatically turn off failure response.set_cookie('Key ' , ' value ' ) return Response
# set cookies failure more than 10 seconds, writing response.set_cookie ( ' Key ' , ' value ' , the max_age = 10 )
# failure log 10 seconds after, written CURRENT_TIME = datetime.datetime.utcnow () current_data = + CURRENT_TIME the datetime.timedelta (= 10 seconds The ) response.set_cookie ( ' Key ' , ' value ' , Expires = current_data)
rep.set_cookie (Key, value, ...) rep.set_signed_cookie (Key, value, salt
= ' Encryption salts ' , ...) parameters: Key, the key value = ' ' , the value of the max_age = None, timeout Expires = None, timeout (IEs Expires The requires, SO SET IT IF hasn ' . T been already) path = ' / ' , which entered into force cookie path, / represents the root path, special: with cookie path can be accessed any url of the page domain = in effect None, cookie domain name Secure = False, HTTPS transmission HttpOnly =False http protocol transmission only, JavaScript can not be acquired (not absolute, the bottom layer can be acquired capture may be covered)
Cookie the salt decryption string, worded as follows: obj
= the HttpResponse ( ' S ' ) obj.set_signed_cookie ( ' username ' , ' Jack ' , salt = ' adfadf ' ) # encrypted by salt request.get_signed_cookie ( ' username ' , salt = ' adfadf ' ) # by decrypting the original salt Note: Get cookies written: request.COOKIES. GET ( ' name ' ) disposed cookies wording: response.set_cookie ( 'key','value')
Examples: FBV implement a login account after 10 seconds, and the decorator checks every URL for the account logged
DEFauth (FUNC): '' 'decorator, check the current tour is the existence of cookies in logname logged account number, if present, proceed to the following function, returns plans to enter the url'' ' DEFInner (Request, * args, **kwargs): v= request.COOKIES.get ('LOGNAME') IF notv: returnthe redirect ('/') returnFUNC (Request, * args, **kwargs) returnInner DEFLogin (Request): '' 'login URL' '' IFRequest.' GET ' : return the render (Request, ' login.html ' ) DEF index (Request): IF request.method == ' GET ' : '' ' GET mode, access to the cookies logname account name, if it returns empty Login page '' ' U = request.COOKIES.get ( ' LOGNAME ' ) IF Not U: return the redirect ( ' / ' ) IF Request.Cookies [ ' LOGNAME ' ] == 'admin': alluser = models.UserName.objects.exclude(uname='admin') else: # loguser = request.session['username'] loguser = request.COOKIES['logname'] alluser = models.UserName.objects.filter(uname=loguser) return render(request, 'index.html', {'u_list': alluser} if request.method == 'POST': '''Account login authentication '' ' LOGNAME = request.POST.get ( ' LOGNAME ' , None) logpwd = request.POST.get ( ' logpwd ' , None) IF models.UserName.objects.filter (the uname = LOGNAME): IF Models .UserName.objects.filter (uname = LOGNAME, upwd = logpwd): # login authentication is successful, rewrite cookie login account, 10 seconds delay the Response = HttpResponse ( ' the ok ' ) response.set_cookie ( ' LOGNAME ' , LOGNAME, 10 = the max_age ) return the Response the else : return HttpResponse ( ' pwderr ' ) the else : return HttpResponse ( ' nmerr ' ) @auth # decorator url to access the account at the time, to verify whether the account is logged DEF account (Request): IF request.method = = ' the GET ' : return the render (Request, ' account.html ' )

CBV implement user login authentication through decorators

from django import views
from django.utils.decorators import method_decorator
@method_decorator(auth,name='dispatch')
class Order(views.View):
    def get(self,request):
        v = request.COOKIES.get('logname')
        return render(request,'index.html',{'current_user':v})

    def post(self,request):
        v = request.COOKIES.get('logname')
        return render(request,'index.html',{'current_user':v

 

Guess you like

Origin www.cnblogs.com/lovershowtime/p/11365710.html