I. cookie
1.1 Background
HTTP protocol is stateless and each request is independent for the server. State can be understood as data generated by the client and server in a session, and statelessness assumes that the data will not be retained. The data generated in the conversation is what we need to preserve, that is to say, to "keep state", and Cookie came into being at the historic moment.
What is cookie 1.2
Key-value pairs stored on client browsers.
1.3 Working Principle
The browser sends requests to the server side, and the server side generates cookies which are sent to the client browser along with the response. Client browsers save cookies locally. When the browser sends the request to the server again, the cookie is automatically carried.
1.4 cookie coverage
Sending duplicate Cookies on the server side will override the original Cookies. For example, the first request server side of the browser sends Cookie is Set-Cookie: x=X; the second request server side sends Set-Cookie: x=XX, then the browser only leaves one Cookie, that is, x=XX.
1.5 View cookie s
Press F12 in the browser and click on network-cookies to see it.
1.6 cookie usage
Setting cookie s
Write cookie s: Write on Httpresponse objects
obj.set_cookie(key,value)
def set_cookie(request): obj = HttpResponse('set_cookie') # stay Httpresponse Write on this object obj.set_cookie('name', 'moon') # Notice that it's a comma. return obj
Getting cookie s
Get cookie: Get it from the request object, and it's a dictionary, request.COOKIES
def get_cookie(request): obj = HttpResponse('get_cookie') print(type(request.COOKIES)) # Dictionary type # take cookie Value print(request.COOKIES) name=request.COOKIES.get('name') return obj # Must return one HttpResponse object
delete cookie
obj.delete_cookie('name')
1.7 Chestnuts (Login Authentication Decorator)
# Sign in def login(request): if request.method == 'GET': return render(request, 'login.html') else: next = request.GET.get('next') # Get the path you want to browse before redirecting to the login page name = request.POST.get('name') pwd = request.POST.get('pwd') if name == 'moon' and pwd == '123': if next: obj = redirect(next) else: obj = redirect('/index/') # If you start with a visit login The page jumps to the home page after successful landing. index obj.set_cookie('is_login', True) # Logon successfully generated cookie return obj else: return HttpResponse('ERROR Incorrect username or password') # Login Authentication Decorator def login_auth(func): def inner(request, *args, **kwargs): # Get the path you visited before url = request.get_full_path() is_login = request.COOKIES.get('is_login') if is_login: res = func(request, *args, **kwargs) return res else: return redirect('/login/?next=%s' % url) @login_auth def shopping(request): return HttpResponse('I'm the shopping page.,I have to log in to see it.')
1.8 Other cookie parameters
- Salted salt=''
- Timeout max_age, passing a second; timeout expires, passing a datatime object
- Path ='/', you can set the path, after setting the path, path='/index /', only when you access index, you will bring cookie s.
- domain=None Sets the valid domain under the domain name ='map. baidu. com'
- Security = False, (default is false, set to True browser will pass cookies back and forth via HTTPS)
- httponly=True can only be transmitted by https protocol and can not be retrieved by JavaScript (not absolutely, the underlying package can be retrieved or overwritten)
def cookie_other(request): object=HttpResponse('ok') # Salt addition salt: 123 It's a password.,solution cookie You need it when you need it., object.set_signed_cookie('name','moon',salt='123') # timeout max_age: Three days object.set_cookie('name','lqz',max_age=60*60*24*3)
session
2.1 Background
Cookies sent to the server to prove their identity are bound to carry personal information, once intercepted or stolen leaked information will be very dangerous, so session came into being.
2.2 What is session?
Key-value pairs stored on the server: {Random String: User Information}, session must be used with cookie s, not only in the database, but also in the file, redis (in-memory database)
2.3 session Working Principle
1. Generating Random Strings
2. De-database Storage
session_key (random string) | session_data (cookie information) | expire_date (timeout) |
3. Write cookie (set_cookie ('session id','random string')
2.4 session usage
The database must be migrated before session is used.
# Set up session request.session['name']='moon' # take session Execution process: # Fetch cookie Random string # take session Queries in tables based on random strings,Query out session_data This dictionary,Then put it in the dictionary. name Return name=request.session['name'] # Delete values # take out cookie,Random string,Deleting random strings from the database is a record of the current value request.session.delete() # Both deleted cookie,Delete the database again request.session.flush()
2.5 session Attribute Complete
# Get, Set, Delete Session Medium data request.session['k1'] request.session.get('k1',None) request.session['k1'] = 123 request.session.setdefault('k1',123) # Existence is not set del request.session['k1'] # All key, value, key-value pairs request.session.keys() request.session.values() request.session.items() request.session.iterkeys() request.session.itervalues() request.session.iteritems() # Conversation session Of key request.session.session_key # All Session Data deletion with expiration date less than current date request.session.clear_expired() # Check sessions session Of key Does it exist in the database? request.session.exists("session_key") # Delete all of the current session Session data(Delete only the database) request.session.delete() # Delete the current session data and delete the session's Cookie(Database and cookie All deleted. request.session.flush() //This is used to ensure that the previous session data is not accessible by the user's browser again //For example, it is called in the django.contrib.auth.logout() function. # Setting Sessions Session and Cookie Overtime request.session.set_expiry(value) * If value It's an integer. session It will fail in a few seconds. * If value It's a datatime or timedelta,session It will fail after that time. * If value It's 0.,User Closes Browser session It will fail. * If value yes None,session Will depend on the overall situation session Failure strategy.