# cookies 和 session
## cookies to record data on the client browser:
For example:
1.
tells the browser to save the data, the next request the content of these data to the server comes
from django.http import HttpResponse
index DEF (Request):
RESP = the HttpResponse ()
resp.set_cookie ( 'Cookies name', cookies values, expiration time)
#resp = the render (Request, 'xxx.html', about locals ())
# resp.set_cookie ( 'Cookies name ', cookies values, expiration time)
return resp
Expiration time: seconds
2. The server browser to see if there is value with cookies
get cookies value:
value = request.COOKIES.get ( 'cookies name')
3. Inform browser empty the cookies value
def xxxxx:
resp = HttpResponse()
resp.delete_cookie('cookies名')
return resp
## session temporary session control data, recorded on the server, will record 'KEY' browser cookies to more records
1. Configure settings.py file, django comes with general initialization
= The INSTALLED_APPS [
# Enable application sessions
'django.contrib.sessions',
]
MIDDLEWARE = [
# Enable Session middleware
'django.contrib.sessions.middleware.SessionMiddleware',
]
2. Set the server to save time: settings.py file increase
SESSION_COOKIE_AGE = 60 * 60 * 24 * 7 * 2 # two weeks to clear the data
SESSION_EXPIRE_AT_BROWSER_CLOSE = True # browser shutdown Clear data
3. Set Add session record
def xxxxx(request):
request.session['KEY'] = VALUE
return HttpResponse()
4. Get session record
VALUE = request.session.get('KEY')
5. Delete recording session
# browser history delete
resp.delete_cookie ( 'SessionID')
# Delete Delete data inside the database is not clean
del makes request.session [ 'KEY']
# Set Time saved to the server, automatically clean and remove