Django provides full support for anonymous sessions. The session framework lets you store and retrieve arbitrary data on a per-site-visitor basis. It stores data on the server side and abstracts the sending and receiving of cookies. Cookies contain a session ID – not the data itself (unless you’re using the cookie based backend).
Django完全支持匿名session。在用户访问当前网站期间,session框架允许你记录(读取)任何数据。所有这些数据都存在服务器端,而且抽象了cookies的发送和接收过程。客户端的cookie中只包括session id,不包含数据本身(除非将session engine设置为django.contrib.sessions.backends.signed_cookies)
Enabling sessions
激活sessionTo enable session functionality, do the following:
- Edit the MIDDLEWARE_CLASSES setting and make sure it contains'django.contrib.sessions.middleware.SessionMiddleware'. The default settings.pycreated by django-admin startproject has SessionMiddleware activated.
Configuring the session engine
session engine配置
Using database-backed sessions
存在数据库中
Using cached sessions
存在缓存中
Warning
You should only use cache-based sessions if you’re using the Memcached cache backend. The local-memory cache backend doesn’t retain data long enough to be a good choice, and it’ll be faster to use file or database sessions directly instead of sending everything through the file or database cache backends. Additionally, the local-memory cache backend is NOT multi-process safe, therefore probably not a good choice for production environments.
- Set SESSION_ENGINE to "django.contrib.sessions.backends.cache" for a simple caching session store. Session data will be stored directly in your cache. However, session data may not be persistent: cached data can be evicted if the cache fills up or if the cache server is restarted.
- ESSION_ENGINE="django.contrib.sessions.backends.cache":数据只存在缓存中,可能因为缓存的替换策略或系统的重启而消失。
- For persistent, cached data, set SESSION_ENGINE to"django.contrib.sessions.backends.cached_db". This uses a write-through cache – every write to the cache will also be written to the database. Session reads only use the database if the data is not already in the cache.
- SESSION_ENGINE="django.contrib.sessions.backends.cached_db":这种方式会将缓存中的数据同时存到数据库中,不过会损失一点性能。如果使用这种方式也需要遵从数据库的存储配置。
Using file-based sessions
存到文件中
Using cookie-based sessions
存到cookie中
在views中使用session
-
__getitem__(
key)
-
Example: fav_color = request.session['fav_color']
-
__setitem__(
key,
value)
-
Example: request.session['fav_color'] = 'blue'
-
__delitem__(
key)
-
Example: del request.session['fav_color']. This raises KeyError if the given key isn’t already in the session.
-
__contains__(
key)
-
Example: 'fav_color' in request.session
-
get(
key,
default=None)
-
Example: fav_color = request.session.get('fav_color', 'red')
-
pop(
key)
-
Example: fav_color = request.session.pop('fav_color')
-
keys()
-
items()
-
setdefault()
-
clear()
It also has these methods:
-
flush()
-
Delete the current session data from the session and delete the session cookie. This is used if you want to ensure that the previous session data can’t be accessed again from the user’s browser (for example, the django.contrib.auth.logout() function calls it).
Changed in Django Development version:Deletion of the session cookie is a behavior new in Django 1.8. Previously, the behavior was to regenerate the session key value that was sent back to the user in the cookie.
-
删除session数据及其对应的cookie, django.contrib.auth.logout()在执行的时候就会调用这个函数。
-
set_test_cookie()
-
Sets a test cookie to determine whether the user’s browser supports cookies. Due to the way cookies work, you won’t be able to test this until the user’s next page request. See Setting test cookies below for more information.
-
测试客户端是否允许使用cookie,不过测试的结果只能在下次接到客户端的请求时才知道。
-
test_cookie_worked()
-
Returns either True or False, depending on whether the user’s browser accepted the test cookie. Due to the way cookies work, you’ll have to call set_test_cookie() on a previous, separate page request. See Setting test cookies below for more information.
-
这个就是获取检测结果的函数,true是允许使用cookie,false是不允许。
-
delete_test_cookie()
-
Deletes the test cookie. Use this to clean up after yourself.
-
测试之外,要删掉测试cookie
-
set_expiry(
value)
-
Sets the expiration time for the session. You can pass a number of different values:
- If value is an integer, the session will expire after that many seconds of inactivity. For example, calling request.session.set_expiry(300) would make the session expire in 5 minutes.
- 如果value是一个整数n,则存活时间就是n秒
- If value is a datetime or timedelta object, the session will expire at that specific date/time. Note that datetime and timedelta values are only serializable if you are using thePickleSerializer.
- 如果value是datetime或timedelta类型的,session会在某个确定的时间点失效。
- If value is 0, the user’s session cookie will expire when the user’s Web browser is closed.
- 如果value是0,则seesion在浏览器关闭时失效
- If value is None, the session reverts to using the global session expiry policy.
Reading a session is not considered activity for expiration purposes. Session expiration is computed from the last time the session was modified.
-
get_expiry_age()
-
Returns the number of seconds until this session expires. For sessions with no custom expiration (or those set to expire at browser close), this will equal SESSION_COOKIE_AGE.
This function accepts two optional keyword arguments:
- modification: last modification of the session, as a datetime object. Defaults to the current time.
- expiry: expiry information for the session, as a datetime object, an int (in seconds), or None. Defaults to the value stored in the session by set_expiry(), if there is one, or None.
-
get_expiry_date()
-
Returns the date this session will expire. For sessions with no custom expiration (or those set to expire at browser close), this will equal the date SESSION_COOKIE_AGE seconds from now.
This function accepts the same keyword arguments as get_expiry_age().
-
get_expire_at_browser_close()
-
Returns either True or False, depending on whether the user’s session cookie will expire when the user’s Web browser is closed.
-
clear_expired()
-
Removes expired sessions from the session store. This class method is called by clearsessions.
-
cycle_key()
-
Creates a new session key while retaining the current session data.django.contrib.auth.login() calls this method to mitigate against session fixation.