A, Cookie
Client technology, storing data information to the browser, the dictionary structure is stored in structure, i.e., key-value.
Cookie server is created, but saved the client, the client sends a request each time a Cookie will send information to the server (because Cookie is part of the request header information)
Cookie does not support Chinese, can not cross-browser, cross-domain can not
1, set a cookie
HttpResponse.set_cookie()
response.set_signed_cookie("Cookie名称","Cookie值",salt="盐")
Properties: key
value
max-age valid duration, in seconds, is designated as 0 disables the browser fails (by default) as the effective value of 100 after 100 seconds expire automatically set to never expire None
datetime expires or a support timedelta, can specify a specific date, expires = timedelta (days = 10) represented by ten days expired
max-age and a two specified xepires
# Normal settings, clear text display DEF the setcookie (Request): Response = the HttpResponse ( ' disposed COOKIE success ' ) response.set_cookie ( ' name ' , ' Egon ' ) return Response
# Salt settings displayed in encrypted form DEF do_login (Request): the uname = request.POST.get ( ' the uname ' ) Response = HttpResponseRedirect (Reverse ( ' App: Mine ' )) # response.set_cookie ( 'the uname', the uname, the max_age = 60) response.set_signed_cookie ( ' Content ' , the uname, " Rock " ) return Response
2, get
HttpRequest.COOKIES.get(key)
request.get_signed_cookie("cookie名称",salt="盐")
def getcookie(request): return HttpResponse(request.COOKIES.get('name'))
def mine(request): # uname = request.COOKIES.get("content") try: uname = request.get_signed_cookie("content", salt="Rock") if uname: # return HttpResponse(uname) return render(request, 'mine.html', context={"uname": uname}) except Exception as e: print("获取失败") return redirect(reverse('app:login'))
3, delete
response.delete_cookie(key)
def logout(request): response = redirect(reverse("app:login")) response.delete_cookie("content") return response
二、Session
Session is used to indicate a "session" of a user and the server. Sent using the client sessionid (in the presence of Cookie) sessionid match with the server, the client requests to find your "session", often used for login authentication.
Session typically stored in memory in Django, use the default database Session Save Session of the way if you want to save changes, we need to add SESSION_ENGINE configuration information can be saved to redis in session.
1, data storage
HttpRequest.session [key] = value, a base64 encoding data
2, the read data
request.session.session_key 获取session_id
HttpRequest.session.get(key)
3, delete session
del request.session["key"]
request.session.flush () clears the cookie and session
request.session.clear () Clears all session
def login(request): if request.method == "GET": return render(request, 'two_login.html') elif request.method == "POST": username = request.POST.get("username") request.session["username"] = username return HttpResponse("登录成功") def mine(request): username = request.session.get("username") print(request.session.session_key) return render(request, 'two_mine.html', context=locals()) def logout(request): response = redirect(reverse('myapp:mine')) # del request.session['username'] # response.delete_cookie('sessionid') # session cookie一起干掉 request.session.flush() return response
4, session important configuration
①、SESSION_EXPIRE_AT_BROWSER_CLOSE = True
When the browser is closed, Clear Local Cookie
②、 SESSION_COOKIE_AGE = 60
Set the number of seconds saved session
5, extension: Save the session to redis
① install django-redis-sessions library
pip install django-redis-sessions
② configuration in settings.py
SESSION_ENGINE = 'redis_sessions.session' SESSION_REDIS = { 'host':'127.0.0.1', 'port':6379, 'db':0, 'password':'Redis密码', 'prefix':"key前缀", 'socket_timeout':5 }
Three, Token
Token to make up for the shortcomings server session technology (server's resources) generated, Token validation of thought is "time for space."
When the first authentication is successful (user name and password are correct), the server user data to generate a signature token, and the token is sent to the client, when the client sends a request, will carry the token to the server, the server decrypting the token authentication, when authentication is successful, then the user authentication. otherwise, validation fails.
1, use
Use in a mobile terminal or client development, generally transmitted in the form of Json, the mobile terminal needs to store its own Token, Token needs to acquire related data when Token passing active