#1. Access Cookies
#1. Set Cookies
# Response. set_cookie ("cookie_key", "value ")
#2. Obtain Cookies
# Value = request. COOKIES ["cookie_key"]
#3. Delete Cookies
# Response. delete_cookie ("cookie_key", path = "/", domain = name)
#4. Cookies
# If "cookie_name" is request. COOKIES:
#5. response. set_cookie () transmits some optional parameter descriptions
# Parameter default value description
# The duration (in seconds) of max_age None cookies. If it is set to None, the cookies will become invalid when the browser is closed.
# Expires None cookie expiration time. Format: "Wdy, DD-Mth-yy hh: MM: ss gmt" If this parameter is set,
# It will overwrite the max_age parameter.
# Path "/" indicates the path prefix in which the cookie takes effect. The browser will only send the cookie back to the page with this path, so that you can avoid
# Send the cookie to other applications on the site.
# This parameter is useful when your application is not at the top of the site.
# Domain None cookie effective site. You can use this parameter to construct a cross-site cookie. For example, domain = ".example.com"
# The constructed cookies are readable for the following websites:Www.example.com, Www2.example.com and
# An.other.sub.domain.example.com.
# If this parameter is set to None, the cookie can only be read by the site where it is set.
# Secure False if it is set to True, the browser will pass the cookie back and forth through HTTPS.
# Cookies
#1. Cookies are stored in dictionaries (Key-> Value Key-Value pairs). For access, you only need to access the Session Key to obtain the Value corresponding to the Key.
# If: value = response. set_cookie ("cookie_key", "value ")
#2. Store data on the client
# Advantages:
# Data is stored on the client, which reduces the pressure on the server and improves the website performance.
# Disadvantages:
#1. Low security: users can easily view or crack session information on the client.
######################################## ##########################
The code is as follows: |
Copy code |
From django. template import Context From django. http import HttpResponse From django. http import HttpResponseRedirect Import datetime
Def set_user (request, hour = 0, name = "admin "):
Dt = datetime. datetime. now () + datetime. timedelta (hours = int (hour )) Html = "Set User % s as logon reply, past time: % s" % (name, str (dt )) Response = HttpResponse (html) Response. set_cookie ("username", name, expires = dt) Return response
Def show_user (request ): Html = "" If "username" in request. COOKIES: Name = request. COOKIES ["username"] If name = "admin ": Html = "User % s Cookies do not time out" % name If name = "loker ": Html = "User % s Cookies do not time out" % name Else: Dt = datetime. datetime. now () + datetime. timedelta (hours = int (1 )) Name = "loker" Html = "your Cookies have timed out. n. Set User % s to logon reply. Past Time: % s" % (name, str (dt )) Response = HttpResponse (html) Response. set_cookie ("username", name, expires = dt) Return response Response = HttpResponse (html)
|
######################################## ######################################## #######
#1. Start the Sessions function: -- normally, you can use the session function without any settings. If you have deleted or modified the configuration, check the configuration.
#1. Edit the MIDDLEWARE_CLASSES configuration in settings. py to ensure that 'Django. contrib. sessions. middleware. SessionMiddleware 'exists. If not, add it.
#2. Edit the INSTALLED_APPS configuration in settings. py to make sure that 'Django. contrib. Session' is enabled. (if you just opened this application, don't forget to run manage. py syncdb)
#
# II. How to use it:
#1. Set the Sessions value
# Request. session ['session _ name'] = "admin"
#2. Obtain the Sessions value
# Session_name = request. session ["session_name"]
#3. Delete the Sessions value
# Del request. session ["session_name"]
#4. Check whether the session value is operated
# If "session_name" is request. session:
# III. sessions rules:
#1. Sessions are stored in a dictionary (Key-> Value Key-Value pairs). For access, you only need to access the session Key to obtain the Value corresponding to the Key.
# If: value = request. session ["key_name"]
#2. The key value starting with an underscore in the Session Dictionary is the key value reserved in Django. The framework only contains session variables starting with a few underscores,
# Unless you know their specific meaning and are willing to keep up with Django's changes, it is best not to use the variables starting with these underscores, they will make D
# Jango disrupt your application.
#3. Do not replace request. session with a new object or access its attributes,
#4. Sessions are stored on the server,
# Advantages: Data storage is relatively secure and convenient for data exchange.
# Disadvantages: if the storage data is large and the access traffic is large, the server resources are consumed, resulting in a decline in the overall performance of the website.
######################################## ######################################## ########
The code is as follows: |
Copy code |
From django. template import Context From django. http import HttpResponse
# Set the Sessions value Def set_session (request, name = ""): # If "username" in request. session: # Del request. session ['User _ name'] Request. session ['User _ name'] = name Return HttpResponse ("Set a session key: % s value: % s" % ("username", name ))
Def del_session (request ): If "user_name" in request. session: Del request. session ['User _ name'] Return HttpResponse ("Clear an item from the session ") # Viewing Sessions values Def show_session (request ): Html = "" If "user_name" in request. session: Name = request. session ["user_name"] If name = "admin ": Html = "Django site administration | Get a session value: % s" % (str (name )) Elif name = "lhj588 ": Html = "Django site | Get a session value: % s" % (str (name )) Elif not name: Html = "Django site | Get a session value is null" Return HttpResponse (html) Else: Return HttpResponse ("Session is null ") # Set_session (request, "loker ")
|
######################################## ##############
# Urls. py configuration
######################################## ###############
The code is as follows: |
Copy code |
From django. conf. urls. defaults import * From django. contrib import admin Admin. autodiscover ()
Urlpatterns = patterns ('', (R' ^ cookies/showuser/$ ', 'Cook. views. show_user '), (R' ^ cookies/setuser/$ ', 'Cook. views. set_user '), (R' ^ session/setuser/(. *)/', 'Cook. views. set_session '), (R' ^ session/showuser/$ ', 'Cook. views. show_session '), (R' ^ session/del/$ ', 'Cook. views. del_session '), ) |
######################################## ######################
# Test
######################################## #####################
1. Test Cookies
Set Cookies for access:Http: // 127.0.0.1: 8000/cookies/setuser/
Access to the display Cookies:Http: // 127.0.0.1: 8000/cookies/showuser/
2. Test Sessions.
Set Session access:Http: // 127.0.0.1: 8000/session/setuser/admin/
Get display Session access:Http: // 127.0.0.1: 8000/session/showuser/
Clear Session access:Http: // 127.0.0.1: 8000/session/del/