1, cookie,
This is the fourth day of my participation in Gwen Challenge
Cookie: Saves status information
A group of key-value pairs saved locally in the browser
Features:
- Set by the server for the browser
- The cookie information is saved locally in the browser, but the browser has the right not to save it
- The browser automatically carries the corresponding cookie when it visits again
Why use cookies?
Http protocol is stateless protocol, each request is independent of each other, there is no way to save the state, use cookies to save the state.
The Cookie specification
Maintains the session by adding cookies to the response header
- The Cookie size limit is 4KB.
- A server saves a maximum of 20 cookies on the client browser.
- A browser can save up to 300 cookies, because one browser can access multiple servers.
- Only one user of a browser can log in to the same site at a time.
Djangos manipulate cookies
# set cookies:
response.set_cookie(key,value) Set cookie :is_login=1
response.set_signed_cookie("key",value,salt="s28") # Encrypt cookies as sessionSet the cookie parameters# max_age = 5 # timeout = 5 seconds
# expires=None, requires expires (IE requires Expires, so set it if hasn't been already)
# path the path where the cookie takes effect '/', the path where the cookie takes effect, / indicates the root path, in particular: the cookie of the root path can be accessed by pages at any URL
# domain=None, the domain name for the Cookie to take effect
# secure=True HTTPS transfers
# httpOnly =True # httpOnly =True # httpOnly =True
# get cookie
request.COOKIES {} Request header cookie :is_login=1
request.get_signed_cookie("key", salt="s28",defalut="") Get the encrypted cookie
Set the cookie value to null and the timeout period to 0
response.delete_cook(key)
# more parameters and data: https://www.cnblogs.com/maple-shaw/articles/9502602.html
Copy the code
Instance of a
# login
def login(request) :
if request.method == "POST":
Get user input
user = request.POST.get("user")
pwd = request.POST.get("pwd")
if user == "abc" and pwd == "123": Save login status to cookie after successful login
# geturl () {return url ();} # geturl ()
url = request.GET.get("url")
if url:
return_url = url
else:
return_url = reverse("publisher")
ret = redirect(return_url)
ret.set_cookie("is_login"."1") Set cookies to 1 (!!! There is no s)
return ret
else:
error = "Incorrect user name and password!"
return render(request, "login.html".locals())
Set cookie to null timeout to 0
def logout(request) :
# delete cookie (key value pair)
ret = redirect("/login/")
ret.delete_cookie("is_login")
Redirect to the login page
return ret
Copy the code
Set the decorator
# Decorator to determine cookies information
def is_cookies(func) :
@wraps(func)
def inner(request, *args, **kwargs) :
print(request.COOKIES)
is_login = request.COOKIES.get("is_login")
ifis_login ! ="1": # 1 means logged in (login is also returned if cookies are cleared)
# not logged in
print(request.path_info) /publishers_list/
return redirect("/login/? url={}".format(request.path_info)) # concatenate to the corresponding URL for return
ret = func(request, *args, **kwargs)
return ret
return inner
Copy the code
Set_cookie (“is_login”, “1”) : Passes the cookie as a dictionary if the login succeeds (“is_login”, “1”)
Then add a decorator to each of the places that need to be determined, and determine if the cookies passed are 1 and return the login page if they are not
1. First it spliced into a URL, and then in the login time to obtain the parameters, you can return to the original URL
Example 2
# No decorators
# views. Py logic
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
def index(request) :
# ret = HttpResponse('ok')
# ret.set_cookie('k1', 'v1')
is_login = request.COOKIES.get('is_login')
if is_login == '0':
return render(request, 'index.html')
return redirect('login')
def login(request) :
if request.method == 'GET':
return render(request, 'login.html')
else:
name = request.POST.get('name')
pwd = request.POST.get('pwd')
print(name, pwd)
if name == 'laowang' and pwd == '123':
ret = redirect('/home/')
ret.set_cookie('is_login'.0)
return ret
else:
return redirect('login')
def home(request) :
# print(request.COOKIES)
is_login = request.COOKIES.get('is_login')
if is_login == '0':
return render(request, 'home.html')
else:
return redirect('login')
Copy the code
# Bring decorators
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
# a decorator
# def wrapper(f):
# def inner(*args, **kwargs):
# """ Add additional functionality: perform the operation before the decorated function.
# ret = f(*args, **kwargs)
Add additional functionality: perform the operation after the decorated function.
# return ret
# return inner
def wrapper(f) :
def inner(request, *args, **kwargs) :
is_login = request.COOKIES.get('is_login')
if is_login == '1':
return f(request, *args, **kwargs)
else:
return redirect('login')
return inner
@wrapper
def index(request) :
return render(request, 'index.html')
@wrapper
def home(request) :
return render(request, 'home.html')
def login(request) :
if request.method == 'GET':
return render(request, 'login.html')
else:
name = request.POST.get('name')
pwd = request.POST.get('pwd')
print(name, pwd)
if name == 'laowang' and pwd == '123':
ret = redirect('/home/')
ret.set_cookie('is_login'.1)
return ret
else:
return redirect('login')
def logout(request) :
rep = redirect("/login/")
rep.delete_cookie("user") Delete the usercookie value from the user's browser
return rep
Copy the code
2, the session
The principle of
Cookies can verify state, but your cookie keys and values are visible in developer mode in the browser. Of course, you can set cookies by encrypting the key-value pair and sending it to the browser. So session is a similar mechanism, where when the browser sends a login request, it randomly sets a cookie value to the browser, a random string called session_id, At the same time and bring your request data (session_data) as key/value pairs stored in a local database (| django_session) in the table, browser with session_id come next time, go to the library to find the corresponding value.Copy the code
Groups of key-value pairs stored on the server, dependent on cookie use
Why use sessions?
1. The cookie is stored locally in the browser, which is insecure. 2. Browsers have certain limits on the size and number of cookiesCopy the code
Process:
- The first request, without cookies, sets a key-value pair, generating a unique identifier based on the browser, for a dictionary.
- Dictionaries are converted to strings (serialization), encrypted, and unique identifiers and strings are stored in the database (django_session)
- Returns a cookie with a unique identifier (sessionID) to the browser
- The next request carries the session_ID. The server finds the corresponding data (session_data) according to the session, decrypts it, serializes it, and obtains the corresponding value according to the key.
Workflow:
(1) When the user accesses the server, the server will generate a random string;
(2) after the user login successfully, {sessionID: random string} is organized into key-value pairs and added to the cookie and sent to the user;
(3) The server takes the random string in the cookie sent to the client as the key, the user information as the value, and saves the user information;
(4) When accessing the service again, the client will bring session_ID, and the server will confirm whether the user has visited the website according to session_ID
The default session timeout is 2 weeks
Djangos session related methods
# set the session
request.session[key] = value
# get
request.session[key] request.session.get(key)
# remove
del request.session[key] request.session.pop(key)
Session key
request.session.session_key
Delete all data whose Session expiration date is less than the current date
request.session.clear_expired()
Check whether the session key exists in the database
request.session.exists("session_key")
Delete all Session data from the current Sessionrequest.session.delete()Delete the current session data and delete the session Cookie.Request. The session. Flush () this is used to ensure that the previous session data can not be the user's browser access again For example, django. Contrib. Auth. Logout () function will invoke it.Set Session timeout and Cookie timeoutRequest.session.set_expiry (Value) * If the value is an integer, the session expires after a few seconds. * If value is a datatime or timedelta, the session expires after that time. * If value is0The session is invalidated when the user closes the browser. * If value isNone, the session will depend on the global session expiration policyCopy the code
Djangos session configuration
From django.conf import global_settings # Global_settings Click global_Settings to view all configuration informationCopy the code
1.Database Session SESSION_ENGINE ='django.contrib.sessions.backends.db' # Engine (default)
2.Cache Session SESSION_ENGINE ='django.contrib.sessions.backends.cache' # engine
SESSION_CACHE_ALIAS = 'default' The cache alias used (default memory cache, or memcache) depends on the cache Settings
3.File Session SESSION_ENGINE ='django.contrib.sessions.backends.file' # engine
SESSION_FILE_PATH = None # Cache file path, if None, use tempFile module to obtain a temporary address tempfile.gettempdir()
4.Cache + database SESSION_ENGINE ='django.contrib.sessions.backends.cached_db' # engine
5.Encrypted Cookie Session SESSION_ENGINE ='django.contrib.sessions.backends.signed_cookies' # engineOther common Settings: SESSION_COOKIE_NAME ="sessionid" Sessionid = random string (default)SESSION_COOKIE_PATH ="/" The path where the Session cookie is saved (default)
SESSION_COOKIE_DOMAIN = None # Session cookie saved domain name (default)
SESSION_COOKIE_SECURE = False # whether to transfer cookies over Https (default)
SESSION_COOKIE_HTTPONLY = True # whether Session cookies only support HTTP transmission (default)
SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) (default)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser so that Session expires (default) the browser relationship is invalid
SESSION_SAVE_EVERY_REQUEST = False # whether to save Session on every request, default to save after modification (default)
Copy the code
Instance of a
# a decorator
def is_cookies(func) :
@wraps(func)
def inner(request, *args, **kwargs) :
print(request.COOKIES)
# is_login = request.cookies. Get ("is_login"
is_login = request.session.get("is_login")
print(is_login,type(is_login))
ifis_login ! =1: # 1 indicates login (which is also returned if cookies are cleared), and session returns an integer
# not logged in
print(request.path_info) /publishers_list/
return redirect("/login/? url={}".format(request.path_info)) # concatenate to the corresponding URL for return
ret = func(request, *args, **kwargs)
return ret
return inner
#login
def login(request) :
if request.method == "POST":
Get user input
user = request.POST.get("user")
pwd = request.POST.get("pwd")
if user == "abc" and pwd == "123": Save login status to cookie after successful login
# geturl () {return url ();} # geturl ()
url = request.GET.get("url")
if url:
return_url = url
else:
return_url = reverse("publisher")
ret = redirect(return_url)
# ret.set_cookie("is_login", "1") There is no s)
request.session["is_login"] = 1 # set the session
return ret
else:
error = "Incorrect user name and password!"
return render(request, "login.html".locals())
Copy the code
Example 2
# session
# views.py
def login(request) :
if request.method == 'GET':
return render(request, 'login.html')
else:
name = request.POST.get('name')
pwd = request.POST.get('pwd')
print(name, pwd)
if name == 'laowang' and pwd == '123':
# ret = redirect('/home/')
# ret.set_cookie('is_login', 0)
# return ret
request.session['is_login'] = True
request.session['username'] = 'bo'
Session_id is generated
# 2. Add a key-value pair to the cookie
# 3. Save to the django.session table
return redirect('/home/')
else:
return redirect('login')
def logout(request) :
request.session.flush() # Know all cookies and sessions
return redirect("/login/")
def home(request) :
print(request.session)
is_login = request.session.get('is_login')
print(is_login, type(is_login)) # bool
if is_login:
return render(request, 'home.html')
else:
return redirect('login')
# return render(request, 'home.html')
def index(request) :
# ret = HttpResponse('ok')
# ret.set_cookie('k1', 'v1')
is_login = request.session.get('is_login')
print(is_login, type(is_login)) # bool
# 1. Session_id from cookie
Django_session = django_session
# 3. Decompress the encrypted user data and obtain the required data
if is_login:
return render(request, 'index.html')
return redirect('login')
# return render(request, 'index.html')
Copy the code
Session information website: www.cnblogs.com/maple-shaw/…
The difference and relation between cookie and session
- The difference between
- Session stores data and server-side cookies on the client
- Cookies are stored on the client and are insecure. Sess is stored on the server and only sesseionID is stored on the client
- Cookies store values on the client side with a size limit of a few kilobytes. There is no limit to sessions
- contact
- Based on the session cookie
conclusion
The article is long, give a big thumbs up to those who see it! Due to the author’s limited level, the article will inevitably have mistakes, welcome friends feedback correction.
If you find this article helpful, please like, comment, and bookmark it
Your support is my biggest motivation!!