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 .
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
# 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
- HttpResponse.delete_cookie(key)
- Delete the specified key Of Cookies, if key Nothing happens if it doesn't exist
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 :
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. .
request.session["KEY"] = VALUE # dict
value = request.session["KEY"]
value = request.session.get("KEY","DEFAULT_VALUE") # Recommended
del request.session["KEY"]
# 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
py manage.py clearsessions
cookies And session Comparison of
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>
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")