Django全面支持匿名会话。 会话框架让你可以存储和取回每个站点访客任意数据。 它在服务器端存储数据, 并以cookies的形式进行发送和接受数据。 Cookie包含一个会话ID - 而不是数据本身(除非您使用基于cookie的后端)。
会话通过一个中间件实现。
要启用会话功能,请执行以下操作:
MIDDLEWARE
设置并确保它包含'django.contrib.sessions.middleware.SessionMiddleware'
。 由django-admin startproject
创建的默认settings.py
已激活SessionMiddleware
。如果您不想使用会话,则最好从MIDDLEWARE
中删除SessionMiddleware
,并从你的INSTALLED_APPS
中删除'django.contrib.sessions'
。
它会为你节省一点性能的开销。
默认情况下,Django将会话存储在数据库中(使用模型django.contrib.sessions.models.Session
)。 虽然这很方便,但在某些设置中,将会话数据存储在别处会更快,因此可以将Django配置为将会话数据存储在文件系统或缓存中。
如果要使用数据库支持的会话,则需要将'django.contrib.sessions'
添加到INSTALLED_APPS
设置中。
配置安装后,运行manage.py migrate
以安装保存会话数据的一张数据库表。
为了获得更好的性能,您可能需要使用基于缓存的会话后端。
要使用Django的缓存系统存储会话数据,您首先需要确保您配置了缓存;有关详细信息,请参阅缓存文档。
警告
如果您使用Memcached缓存后端,则只应使用基于缓存的会话。 基于本地内存的缓存系统不会长时间保留数据,所以不是一个好的选择,而且直接使用文件或数据库会话比通过文件或数据库缓存系统要快。 另外,基于本地内存的缓存系统不是多进程安全的,所以对于生产环境可能不是一个好的选择。
如果您在CACHES
中定义了多个缓存,Django将使用默认缓存。 要使用另一个缓存,请将SESSION_CACHE_ALIAS
设置为该缓存的名称。
一旦你的缓存配置好了,你就有两种选择如何将数据存储在缓存中:
SESSION_ENGINE
为"django.contrib.sessions.backends.cache"
。 会话数据将直接存储在缓存中。 但是,会话数据可能不是持久性的:如果缓存填满或缓存服务器重新启动,缓存的数据可能会被清理掉。SESSION_ENGINE
设置为"django.contrib.sessions.backends.cached_db"
。 这使用直写式高速缓存 - 每当数据写入缓存时,也将写入数据库。 读取会话数据时,仅当数据不在缓存中时,读取数据库。两个会话存储都非常快,但简单缓存更快,因为它忽略了持久性。 大部分情况下,cached_db
后端已经足够快,但是如果你需要榨干最后一点的性能,并且接受会话数据丢失的风险,那么你可使用cache
后端。
如果使用cached_db
会话后端,则还需要遵循使用数据库支持的会话的配置说明。
要使用基于文件的会话,请将SESSION_ENGINE
设置为"django.contrib.sessions.backends.file"
。
你可能还想设置SESSION_FILE_PATH
(它的默认值来自tempfile.gettempdir()
的输出,大部分情况是/tmp
)来控制Django在哪里存储会话文件。 请保证你的Web服务器具有读取和写入这个位置的权限。
要使用基于cookies的会话,请将SESSION_ENGINE
设置为"django.contrib.sessions.backends.signed_cookies"
。 此时,会话数据的存储将使用Django 的加密签名工具和SECRET_KEY
设置
注意
建议您将SESSION_COOKIE_HTTPONLY
设置保留为True
以防止从JavaScript访问存储的数据。
警告
如果SECRET_KEY没有保密,并且您正在使用
PickleSerializer
, 这可能导致任意远程代码执行。
拥有SECRET_KEY
的攻击者不仅可以篡改生成被你的站点信任的会话数据,而且可以远程执行任何代码,就像数据是通过pickle序列化过的一样。
如果您使用基于Cookie的会话,请格外注意你的安全秘钥对于任何可以远程访问的系统都是永远完全保密的。
会话数据经过签名但没有加密。
如果使用基于Cookie的会话,则会话数据可以被客户端读取。
MAC(消息认证码)被用来保护数据不被客户端修改,所以被篡改的会话数据将是变成失效的。 如果保存Cookie的客户端(例如你的浏览器)不能保存所有的会话Cookie或丢失数据,会话同样会变得失效。 即便Django会压缩数据,仍然完全有可能超过每个cookie4096个字节的常规限制。
没有更新保证
还要注意,虽然MAC可以保证数据的权威性(由你的站点生成,而不是任何其他人)和完整性(包含全部的数据并且是正确的),它不能保证是最新的,例如返回给你发送给客户端的最新的数据。 这意味着对于某些会话数据的使用,基于Cookie可能让你受到重放攻击(replay attacks)。 其它方式的会话后端在服务器端保存每个会话并在用户登出时使它无效,基于Cookie 的会话在用户登出时不会失效。 因此,如果一个攻击者盗取用户的Cookie,它们可以使用这个Cookie 来以这个用户登录即使用户已登出。 Cookies 只能被当做是“过期的”,如果它们比你的SESSION_COOKIE_AGE
要旧。
性能
最后,Cookie的大小可能会影响您网站的速度。
当SessionMiddleware
被激活时,每个HttpRequest
对象 - 任何Django视图函数的第一个参数 - 将具有有一个session
属性,这是一个类字典对象。
你可以在你的视图中的任何位置读写request.session
。
你可以多次编辑它。
backends.base.
SessionBase
¶这是所有会话对象的基类。 它有以下的标准字典方法:
__getitem__
(key)¶例如: fav_color = request.session['fav_color']
__setitem__
(key, value)¶例如: request.session['fav_color'] = 'blue'
__delitem__
(key)¶例如: del request.session['fav_color']
. 如果给定的key
在session中不存在,则会引发KeyError
。
__contains__
(key)¶例如: 'fav_color' in request.session
get
(key, default=None)¶例如: fav_color = request.session.get('fav_color', 'red')
pop
(key, default=__not_given)¶例如: fav_color = request.session.pop('fav_color', 'blue')
keys
()¶items
()¶setdefault
()¶clear
()¶它还具有下列方法:
flush
()¶从会话中删除当前会话数据并删除会话cookie。 如果要确保先前的会话数据不能从用户的浏览器再次访问(例如,django.contrib.auth.logout()
函数调用它),则使用此方法。
设置测试Cookie以确定用户的浏览器是否支持Cookie。 因为Cookie的工作方式,只有到用户的下一个页面才能验证。 请参阅下面的设置测试cookie了解更多信息。
根据用户的浏览器是否接受测试Cookie,返回True
或False
。 由于Cookie的工作方式,您必须在先前的单独页面请求中调用set_test_cookie()
。
请参阅下面的设置测试cookie了解更多信息。
删除测试cookie。 用它来清理测试cookie。
set_expiry
(value)¶设置会话的到期时间。 您可以传递许多不同的值:
value
是一个整数,那么会话将在经过value值的秒钟不活动之后过期。 例如,调用request.session.set_expiry(300)
会使会话在5分钟后过期。value
是datetime
或timedelta
对象,则会话将在该特定日期/时间过期。 注意datetime
和timedelta
值只有在你使用PickleSerializer
时才可序列化。value
是0
,用户的会话cookie将在用户的Web浏览器关闭时过期。value
为None
,会话将恢复为使用全局会话到期策略。过期的计算不考虑读取会话的操作。 会话有效期从上次会话修改时计算。
get_expiry_age
()¶返回此会话到期之前的秒数。 对于没有自定义过期设置的会话(或设置为在浏览器关闭时过期的会话),这将等于SESSION_COOKIE_AGE
。
该函数接受两个可选的关键字参数:
modification
:会话的最后一次修改时间,类型为一个datetime
对象。 默认为当前时间。expiry
:会话的到期信息,类型为datetime
对象,或者是int
类型(以秒为单位)或None
。 默认为通过set_expiry()
存储在会话中的值,或者为None
。get_expiry_date
()¶返回此会话过期的日期。 对于没有自定义过期的会话(或设置为在浏览器关闭时过期的会话),它将等于从现在开始SESSION_COOKIE_AGE
秒后的日期。
该函数接受与get_expiry_age()
相同的关键字参数。
get_expire_at_browser_close
()¶根据当用户的Web浏览器关闭时用户的会话cookie是否过期,返回True
或False
。
clear_expired
()¶从会话存储中删除过期的会话。 这个类方法由clearsessions
调用。
cycle_key
()¶创建新的session key,并保留当前会话数据。
django.contrib.auth.login()
调用此方法来减轻"会话固定(session fixation)"攻击。
By default, Django serializes session data using JSON. You can use the
SESSION_SERIALIZER
setting to customize the session serialization
format. Even with the caveats described in Write your own serializer, we highly
recommend sticking with JSON serialization especially if you are using the
cookie backend.
For example, here’s an attack scenario if you use pickle
to serialize
session data. If you’re using the signed cookie session backend and SECRET_KEY
is known by an attacker
(there isn’t an inherent vulnerability in Django that would cause it to leak),
the attacker could insert a string into their session which, when unpickled,
executes arbitrary code on the server. The technique for doing so is simple and
easily available on the internet. Although the cookie session storage signs the
cookie-stored data to prevent tampering, a SECRET_KEY
leak
immediately escalates to a remote code execution vulnerability.
serializers.
JSONSerializer
¶A wrapper around the JSON serializer from django.core.signing
. Can
only serialize basic data types.
In addition, as JSON supports only string keys, note that using non-string
keys in request.session
won’t work as expected:
>>> # initial assignment
>>> request.session[0] = 'bar'
>>> # subsequent requests following serialization & deserialization
>>> # of session data
>>> request.session[0] # KeyError
>>> request.session['0']
'bar'
Similarly, data that can’t be encoded in JSON, such as non-UTF8 bytes like
'\xd9'
(which raises UnicodeDecodeError
), can’t be stored.
See the Write your own serializer section for more details on limitations of JSON serialization.
serializers.
PickleSerializer
¶Supports arbitrary Python objects, but, as described above, can lead to a
remote code execution vulnerability if SECRET_KEY
becomes known
by an attacker.
Note that unlike PickleSerializer
,
the JSONSerializer
cannot handle
arbitrary Python data types. As is often the case, there is a trade-off between
convenience and security. If you wish to store more advanced data types
including datetime
and Decimal
in JSON backed sessions, you will need
to write a custom serializer (or convert such values to a JSON serializable
object before storing them in request.session
). While serializing these
values is fairly straightforward
(DjangoJSONEncoder
may be helpful),
writing a decoder that can reliably get back the same thing that you put in is
more fragile. For example, you run the risk of returning a datetime
that
was actually a string that just happened to be in the same format chosen for
datetime
s).
Your serializer class must implement two methods,
dumps(self, obj)
and loads(self, data)
, to serialize and deserialize
the dictionary of session data, respectively.
request.session
. This
is more of a convention than a hard-and-fast rule.request.session
with a new object, and don’t access or
set its attributes. Use it like a Python dictionary.This simplistic view sets a has_commented
variable to True
after a user
posts a comment. It doesn’t let a user post a comment more than once:
def post_comment(request, new_comment):
if request.session.get('has_commented', False):
return HttpResponse("You've already commented.")
c = comments.Comment(comment=new_comment)
c.save()
request.session['has_commented'] = True
return HttpResponse('Thanks for your comment!')
This simplistic view logs in a “member” of the site:
def login(request):
m = Member.objects.get(username=request.POST['username'])
if m.password == request.POST['password']:
request.session['member_id'] = m.id
return HttpResponse("You're logged in.")
else:
return HttpResponse("Your username and password didn't match.")
…And this one logs a member out, according to login()
above:
def logout(request):
try:
del request.session['member_id']
except KeyError:
pass
return HttpResponse("You're logged out.")
The standard django.contrib.auth.logout()
function actually does a bit
more than this to prevent inadvertent data leakage. It calls the
flush()
method of request.session
.
We are using this example as a demonstration of how to work with session
objects, not as a full logout()
implementation.
As a convenience, Django provides an easy way to test whether the user’s
browser accepts cookies. Just call the
set_test_cookie()
method of
request.session
in a view, and call
test_cookie_worked()
in a subsequent view –
not in the same view call.
This awkward split between set_test_cookie()
and test_cookie_worked()
is necessary due to the way cookies work. When you set a cookie, you can’t
actually tell whether a browser accepted it until the browser’s next request.
It’s good practice to use
delete_test_cookie()
to clean up after
yourself. Do this after you’ve verified that the test cookie worked.
Here’s a typical usage example:
from django.http import HttpResponse
from django.shortcuts import render
def login(request):
if request.method == 'POST':
if request.session.test_cookie_worked():
request.session.delete_test_cookie()
return HttpResponse("You're logged in.")
else:
return HttpResponse("Please enable cookies and try again.")
request.session.set_test_cookie()
return render(request, 'foo/login_form.html')
Note
The examples in this section import the SessionStore
object directly
from the django.contrib.sessions.backends.db
backend. In your own code,
you should consider importing SessionStore
from the session engine
designated by SESSION_ENGINE
, as below:
>>> from importlib import import_module
>>> from django.conf import settings
>>> SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
An API is available to manipulate session data outside of a view:
>>> from django.contrib.sessions.backends.db import SessionStore
>>> s = SessionStore()
>>> # stored as seconds since epoch since datetimes are not serializable in JSON.
>>> s['last_login'] = 1376587691
>>> s.create()
>>> s.session_key
'2b1189a188b44ad18c35e113ac6ceead'
>>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
>>> s['last_login']
1376587691
SessionStore.create()
is designed to create a new session (i.e. one not
loaded from the session store and with session_key=None
). save()
is
designed to save an existing session (i.e. one loaded from the session store).
Calling save()
on a new session may also work but has a small chance of
generating a session_key
that collides with an existing one. create()
calls save()
and loops until an unused session_key
is generated.
If you’re using the django.contrib.sessions.backends.db
backend, each
session is just a normal Django model. The Session
model is defined in
django/contrib/sessions/models.py
. Because it’s a normal model, you can
access sessions using the normal Django database API:
>>> from django.contrib.sessions.models import Session
>>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
>>> s.expire_date
datetime.datetime(2005, 8, 20, 13, 35, 12)
Note that you’ll need to call
get_decoded()
to get the session
dictionary. This is necessary because the dictionary is stored in an encoded
format:
>>> s.session_data
'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
>>> s.get_decoded()
{'user_id': 42}
By default, Django only saves to the session database when the session has been modified – that is if any of its dictionary values have been assigned or deleted:
# Session is modified.
request.session['foo'] = 'bar'
# Session is modified.
del request.session['foo']
# Session is modified.
request.session['foo'] = {}
# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session.
request.session['foo']['bar'] = 'baz'
In the last case of the above example, we can tell the session object
explicitly that it has been modified by setting the modified
attribute on
the session object:
request.session.modified = True
To change this default behavior, set the SESSION_SAVE_EVERY_REQUEST
setting to True
. When set to True
, Django will save the session to the
database on every single request.
Note that the session cookie is only sent when a session has been created or
modified. If SESSION_SAVE_EVERY_REQUEST
is True
, the session
cookie will be sent on every request.
Similarly, the expires
part of a session cookie is updated each time the
session cookie is sent.
The session is not saved if the response’s status code is 500.
You can control whether the session framework uses browser-length sessions vs.
persistent sessions with the SESSION_EXPIRE_AT_BROWSER_CLOSE
setting.
By default, SESSION_EXPIRE_AT_BROWSER_CLOSE
is set to False
,
which means session cookies will be stored in users’ browsers for as long as
SESSION_COOKIE_AGE
. Use this if you don’t want people to have to
log in every time they open a browser.
If SESSION_EXPIRE_AT_BROWSER_CLOSE
is set to True
, Django will
use browser-length cookies – cookies that expire as soon as the user closes
their browser. Use this if you want people to have to log in every time they
open a browser.
This setting is a global default and can be overwritten at a per-session level
by explicitly calling the set_expiry()
method
of request.session
as described above in using sessions in views.
Note
Some browsers (Chrome, for example) provide settings that allow users to
continue browsing sessions after closing and re-opening the browser. In
some cases, this can interfere with the
SESSION_EXPIRE_AT_BROWSER_CLOSE
setting and prevent sessions
from expiring on browser close. Please be aware of this while testing
Django applications which have the
SESSION_EXPIRE_AT_BROWSER_CLOSE
setting enabled.
As users create new sessions on your website, session data can accumulate in
your session store. If you’re using the database backend, the
django_session
database table will grow. If you’re using the file backend,
your temporary directory will contain an increasing number of files.
To understand this problem, consider what happens with the database backend.
When a user logs in, Django adds a row to the django_session
database
table. Django updates this row each time the session data changes. If the user
logs out manually, Django deletes the row. But if the user does not log out,
the row never gets deleted. A similar process happens with the file backend.
Django does not provide automatic purging of expired sessions. Therefore,
it’s your job to purge expired sessions on a regular basis. Django provides a
clean-up management command for this purpose: clearsessions
. It’s
recommended to call this command on a regular basis, for example as a daily
cron job.
Note that the cache backend isn’t vulnerable to this problem, because caches automatically delete stale data. Neither is the cookie backend, because the session data is stored by the users’ browsers.
A few Django settings give you control over session behavior:
Subdomains within a site are able to set cookies on the client for the whole domain. This makes session fixation possible if cookies are permitted from subdomains not controlled by trusted users.
For example, an attacker could log into good.example.com
and get a valid
session for their account. If the attacker has control over bad.example.com
,
they can use it to send their session key to you since a subdomain is permitted
to set cookies on *.example.com
. When you visit good.example.com
,
you’ll be logged in as the attacker and might inadvertently enter your
sensitive personal data (e.g. credit card info) into the attackers account.
Another possible attack would be if good.example.com
sets its
SESSION_COOKIE_DOMAIN
to "example.com"
which would cause
session cookies from that site to be sent to bad.example.com
.
json
serializable value when using
JSONSerializer
or any
picklable Python object when using
PickleSerializer
. See the
pickle
module for more information.django_session
.SessionStore
object¶When working with sessions internally, Django uses a session store object from
the corresponding session engine. By convention, the session store object class
is named SessionStore
and is located in the module designated by
SESSION_ENGINE
.
All SessionStore
classes available in Django inherit from
SessionBase
and implement data manipulation methods,
namely:
exists()
create()
save()
delete()
load()
clear_expired()
In order to build a custom session engine or to customize an existing one, you
may create a new class inheriting from SessionBase
or
any other existing SessionStore
class.
Extending most of the session engines is quite straightforward, but doing so with database-backed session engines generally requires some extra effort (see the next section for details).
Creating a custom database-backed session engine built upon those included in
Django (namely db
and cached_db
) may be done by inheriting
AbstractBaseSession
and either SessionStore
class.
AbstractBaseSession
and BaseSessionManager
are importable from
django.contrib.sessions.base_session
so that they can be imported without
including django.contrib.sessions
in INSTALLED_APPS
.
base_session.
AbstractBaseSession
¶The abstract base session model.
session_key
¶Primary key. The field itself may contain up to 40 characters. The current implementation generates a 32-character string (a random sequence of digits and lowercase ASCII letters).
session_data
¶A string containing an encoded and serialized session dictionary.
expire_date
¶A datetime designating when the session expires.
Expired sessions are not available to a user, however, they may still
be stored in the database until the clearsessions
management
command is run.
get_session_store_class
()¶Returns a session store class to be used with this session model.
get_decoded
()¶Returns decoded session data.
Decoding is performed by the session store class.
You can also customize the model manager by subclassing
BaseSessionManager
:
base_session.
BaseSessionManager
¶encode
(session_dict)¶Returns the given session dictionary serialized and encoded as a string.
Encoding is performed by the session store class tied to a model class.
save
(session_key, session_dict, expire_date)¶Saves session data for a provided session key, or deletes the session in case the data is empty.
Customization of SessionStore
classes is achieved by overriding methods
and properties described below:
backends.db.
SessionStore
¶Implements database-backed session store.
get_model_class
()¶Override this method to return a custom session model if you need one.
create_model_instance
(data)¶Returns a new instance of the session model object, which represents the current session state.
Overriding this method provides the ability to modify session model data before it’s saved to database.
backends.cached_db.
SessionStore
¶Implements cached database-backed session store.
cache_key_prefix
¶A prefix added to a session key to build a cache key string.
The example below shows a custom database-backed session engine that includes an additional database column to store an account ID (thus providing an option to query the database for all active sessions for an account):
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.contrib.sessions.base_session import AbstractBaseSession
from django.db import models
class CustomSession(AbstractBaseSession):
account_id = models.IntegerField(null=True, db_index=True)
@classmethod
def get_session_store_class(cls):
return SessionStore
class SessionStore(DBStore):
@classmethod
def get_model_class(cls):
return CustomSession
def create_model_instance(self, data):
obj = super().create_model_instance(data)
try:
account_id = int(data.get('_auth_user_id'))
except (ValueError, TypeError):
account_id = None
obj.account_id = account_id
return obj
If you are migrating from the Django’s built-in cached_db
session store to
a custom one based on cached_db
, you should override the cache key prefix
in order to prevent a namespace clash:
class SessionStore(CachedDBStore):
cache_key_prefix = 'mysessions.custom_cached_db_backend'
# ...
The Django sessions framework is entirely, and solely, cookie-based. It does not fall back to putting session IDs in URLs as a last resort, as PHP does. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the “Referer” header.
Jan 17, 2018