Cookie
Get Cookie
request.COOKIES['key'] request.get_signed_cookie('key', default=RAISE_ERROR, salt='', max_age=None)
The parameters of get_signed_cookie method:
- default: default value
- Salt: Encrypted salt
- max_age: Background control expiration time
Set Cookie
rep = HttpResponse(...) rep = render(request, ...) rep.set_cookie(key,value,...) rep.set_signed_cookie(key,value,salt='Encrypted salt',...)
Parameters:
- Key, key
- Value=', value
- max_age=None, timeout
- expires=None, time-out (IE required expires, so set it if hasn't been already.)
- Path='/', the path that Cookie takes effect, / represents the root path, special: the cookie of the root path can be accessed by any url's page.
- domain=None, Cookie's valid domain name
- secure=False, https transport
- httponly=False can only be transmitted by http protocol and can not be retrieved by JavaScript (not absolutely, the underlying package can be retrieved or overwritten)
Delete Cookie
def logout(request): rep = redirect("/login/") rep.delete_cookie("user") # Delete the cookie value of the user previously set on the user's browser return rep
Examples of Cookie version login verification
def check_login(func): @wraps(func) def inner(request, *args, **kwargs): next_url = request.get_full_path() if request.get_signed_cookie("login", salt="SSS", default=None) == "yes": # Users who have logged in... return func(request, *args, **kwargs) else: # Users who are not logged in, jump to the login page return redirect("/login/?next={}".format(next_url)) return inner def login(request): if request.method == "POST": username = request.POST.get("username") passwd = request.POST.get("password") if username == "xxx" and passwd == "dashabi": next_url = request.GET.get("next") if next_url and next_url != "/logout/": response = redirect(next_url) else: response = redirect("/class_list/") response.set_signed_cookie("login", "yes", salt="SSS") return response return render(request, "login.html")
Session
Session correlation method in Django
# Get, Set, and Delete Data in Session 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() # key of session 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 for the current session request.session.delete() # Delete the current session data and delete the Cookie of the session. 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 Session and Cookie timeouts for sessions request.session.set_expiry(value) # If value is an integer, session s will fail in seconds. # If value is a datatime or timedelta, session will fail after that time. # If value is 0, the user closes the browser session and fails. # If value is None,session will depend on the global session failure policy.
Session configuration in Django
1. data base 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), where the alias depends on the cache settings 3. file Session SESSION_ENGINE = 'django.contrib.sessions.backends.file' # engine SESSION_FILE_PATH = None # Cache file path, if it is None, then use tempfile module to get a temporary address tempfile.gettempdir() 4. cache+data base SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # engine 5. encryption Cookie Session SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' # engine //Other public settings: SESSION_COOKIE_NAME = "sessionid" # Session cookie s are saved on browsers as key, i.e. session ID = random string (default) SESSION_COOKIE_PATH = "/" # Session cookie saved path (default) SESSION_COOKIE_DOMAIN = None # Session cookie saved domain name (default) SESSION_COOKIE_SECURE = False # Whether Https transfers cookie s (default) SESSION_COOKIE_HTTPONLY = True # Whether Session cookie s only support http transport (default) SESSION_COOKIE_AGE = 1209600 # Session cookie expiration date (2 weeks) (default) SESSION_EXPIRE_AT_BROWSER_CLOSE = False # Whether to close the browser to expire Session (default) SESSION_SAVE_EVERY_REQUEST = False # Whether to save Session for each request, after default modification (default)
Example of Session version login validation
from functools import wraps def check_login(func): @wraps(func) def inner(request, *args, **kwargs): next_url = request.get_full_path() if request.session.get("user"): return func(request, *args, **kwargs) else: return redirect("/login/?next={}".format(next_url)) return inner def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") if user == "alex" and pwd == "alex1234": # Setting session request.session["user"] = user # Get the URL before jumping to the landing page next_url = request.GET.get("next") # If so, jump back to the URL before landing. if next_url: return redirect(next_url) # Otherwise, jump to index page by default else: return redirect("/index/") return render(request, "login.html") @check_login def logout(request): # Delete all session s associated with the current request request.session.delete() return redirect("/login/") @check_login def index(request): current_user = request.session.get("user", None) return render(request, "index.html", {"user": current_user})