程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Cookies and sessions in Django

編輯:Python

One 、 What is conversation

conversation : It refers to accessing a website from a browser , End this visit by closing the browser , It's called a conversation . and HTTP Protocol is stateless , It makes the conversation difficult to maintain . If the session cannot be maintained , When we are browsing the website, we will log in frequently , Or double payment, etc .

Cookies And Session Is to Keep session state And the birth of two storage technologies .

cookies It is stored in the storage space of the client browser , stay chrome The browser is displayed as shown in the figure .

Two 、Cookies

2.1 Cookies An introduction to the

  • Cookies Is stored in the browser with Key value pair Stored in the form of , Both keys and values are in the form of ASCII String storage
  • Stored data has a lifecycle
  • cookies The data in is stored and isolated by domain , Cannot access between different domains
  • cookies The internal data of will be carried to the server every time you visit this website , if cookies Larger will reduce the response speed

2.2 Cookies Use

  • cookies---- Storage
HttpResponse.set_cookie(key: Any,value: str = '',
max_age: Any = None,
expires: Any = None)
- key:cookie Name
- value:cookie Value
- max_age: Survival time , The unit is seconds
- expires: Specific expiration time
- When you don't specify max_age And expires when , This data is invalid when the browser is closed
  • Cookies---- obtain
# adopt request.COOKIES The bound dictionary gets the client's COOKIES data 
value = request.COOKIES.get(key," The default value is ") # if key non-existent , Returns the default value 
  • Cookies---- Delete
- HttpResponse.delete_cookie(key)
- Delete the specified key Of Cookies, if key Nothing happens if it doesn't exist
  • Cookies Session keeping login process

3、 ... and 、Session

3.1 Session An introduction to the

  • cookie Is to store data on the browser , and session Is to store data on the server .

  • session It is to open up a space on the server to retain important data when the browser interacts with the server .

Realization way :

  • Use session You need to start in the browser client cookie, And in cookie Storage in sessionid
  • Each client can have an independent server on the server side Session
  • Different requesters will not share this data , One to one correspondence with the requester

3.2 Session Use

session Object is a dictionary like Session Store Type object , It can be operated in a way similar to a dictionary .session Can store strings 、 integer 、 Dictionaries 、 List etc. .

  • preservation Session Value to server :
request.session["KEY"] = VALUE # dict
  • obtain session Value
value = request.session["KEY"]
value = request.session.get("KEY","DEFAULT_VALUE") # Recommended 
  • Delete session
del request.session["KEY"]
  • settings.py Related configuration items
# 1. Appoint sessionid stay cookies Often ( The default is two weeks )
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2
# 2. Set as long as the browser is closed ,session Is the failure , The default is False
SESSION_EXOIRE_AT_BEOWSER_CLOSE = True

Be careful : Django Medium session Data stored in database , So use session You need to ensure that the migration command has been executed .

py manage.py makemigrations
py manage.py migrate

3.3 Django session Existing problems

  • django_session Represents a single table design ; The data volume will continue to grow , Because the browser deliberately deleted sessionid& Expired data not deleted ;
  • You can set a scheduled task to delete expired session data
py manage.py clearsessions

cookies And session Comparison of

species Storage location Security cookies browser Relatively unsafe session The server A relatively safe

Four 、Cookies And Session Session retention process

4.1 session And cookies Solid line automatic login

def login(request):
if request.method == "POST":
# Check login status , If you log in , Show logged in 
if requset.session.get("username") and request.session.get("uid"):
return HttpResponse(" User logged in ")
username = request.COOKIES.get("username")
uid = request.COOKIES.get("uid")
elif username and uid:
# if cookies There is , Then you need to save session, Called write back session
request.session["username"] = username
request.session["uid"] = uid
return HttpResponse(" User logged in ")
else:
return render(request,"login.html")
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
{% if request.session.username %}
<p>hello,{
{ request.session.username }}</p>
<p><a href="/user/exit"> Log out </a></p>
<p><a href=""> My notes </a></p>
{% else %}
{% if request.COOKIES.username %}
<p>hello,{
{ request.COOKIES.username }}</p>
<p><a href="/user/exit"> Log out </a></p>
<p><a href=""> My notes </a></p>
{% else %}
<a href="/user/login_view"> Sign in </a>
<a href="/user/reg_view"> register </a>
{% endif %}
{% endif %}
</body>
</html>

4.2 session And cookie Verify login status

  • The core approach : utilize Python Decorator

4.3 Python Decorator

Closure : Nest another function in the function , And references variables of external functions .

def outer(X):
def inner(y):
return x + y
return inner

outer Within the function , Another definition of inner function , also inner Function also refers to external functions outer The variable of x, This is called a closure . When the output ,outer(6)(5), The value passed in the first parenthesis returns inner function , In fact, that is 6 + y, So pass in the second parameter , You can get the return value ,6 + 5. That is, the first bracket is the outer parameter , The second item number is the inner parameter .

Decorator : It's actually a closure , Is an application of closures .Python Decorator is a function used to expand the function , What's special about this function is that its return value is also a function , Use Python The advantage of decorator is that it does not need to change the code of the original function , Add new functions to functions , When using, just add @demo that will do .

def debug(func):
def wrapper():
print("[DEBUG]:enter{}()".format(func.__name__))
return func()
return wrapper
@debug
def hello():
print("hello")
hello()

In the example, the decorator adds the debug Pattern , Complete this function without modifying the original function code .

# Of course, decorative functions can also pass parameters .
def logging(level):
def outwrapper(func):
def wrapper(*args, **kwargs):
print("[{0}]: enter {1}()".format(level, func.__name__))
return func(*args, **kwargs)
return wrapper
return outwrapper
@logging(level="INFO")
def hello(a, b, c):
print(a, b, c)
hello("hello,","good","morning")

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved