How to use sessions

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

激活session
Sessions are implemented via a piece of  middleware .
session是通过中间件SessionMiddleware实现的。

To 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.
使用session之前需要确保MIDDLEWARE_CLASSES中已经包含了django.contrib.sessions.middleware.SessionMiddleware,默认情况下是包含的。

Configuring the session engine

session engine配置

By default, Django stores sessions in your database (using the model django.contrib.sessions.models.Session ). Though this is convenient, in some setups it’s faster to store session data elsewhere, so Django can be configured to store session data on your filesystem or in your cache.
seesion中的数据默认情况下存储在服务器端的数据库表中(表名:django_session,model:django.contrib.sessions.models.Session)。虽然这样用起来很方便,在有些时候,session中的数据存在其他地方效率可能会更高。因此django允许自定义其他存储方式(文件或缓存)。

Using database-backed sessions

存在数据库中

If you want to use a database-backed session, you need to add 'django.contrib.sessions' to your INSTALLED_APPS setting.
确保INSTALLED_APPS中已经包含了django.contrib.sessions。如果是新添加的,需要执行manage.py migrate使其生效。

Using cached sessions

存在缓存中

For better performance, you may want to use a cache-based session backend.
基于缓存的存储方式可以提高整体的效率。

To store session data using Django’s cache system, you’ll first need to make sure you’ve configured your cache; see the  cache documentation  for details.
如果想采用这种方式需要事先配置好缓存系统,具体可参考以上链接。

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.


警告
缓存系统最好自己配置(比如基于Memcached的缓存系统)。基于本地内存的缓存是不可靠的,因为数据不能保证长期存在那,而且有时候还不如直接用文件/数据库的方式的快。除此之外,对多线程的支持也不好。

If you have multiple caches defined in CACHES, Django will use the default cache. To use another cache, set SESSION_CACHE_ALIAS to the name of that cache.
如果在settings.py中的CACHES中配置了多个,django会使用moren的那个,不过可以通过设置SESSION_CACHE_ALIAS 来指定使用哪个缓存。

Once your cache is configured, you’ve got two choices for how to store data in the cache:
一旦配置好缓存,接下来还有有两种具体的存储方案供你选择。

  • 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

存到文件中

SESSION_ENGINE="django.contrib.sessions.backends.file".
这种方式还需要设置一下存储路径(SESSION_FILE_PATH),默认情况下是tempfile.gettempdir(), 一般是/tmp。

Using cookie-based sessions

存到cookie中

 SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies"
数据的存储会通过django的数据签名(cryptographic signing)工具以及SCRET_KEY设置来实现。在这种方式下,建议同时设置 SESSION_COOKIE_HTTPONLY =True来阻止javascript代码来读取cookie(放置xss攻击的一种的方式)

在views中使用session

对session中数据的存取是通过request.seesion实现的。
__getitem__( key)

Example: fav_color = request.session['fav_color']

__setitem__( keyvalue)

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( keydefault=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.




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值