How to use sessionsLink to this heading
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).
Enabling sessionsLink to this heading
Sessions are implemented via a piece of middleware.
To enable session functionality, do the following:
Edit the
MIDDLEWAREsetting and make sure it contains'django.contrib.sessions.middleware.SessionMiddleware'. The defaultsettings.pycreated bydjango-admin startprojecthasSessionMiddlewareactivated.
If you don't want to use sessions, you might as well remove the
SessionMiddleware line from MIDDLEWARE and
'django.contrib.sessions' from your INSTALLED_APPS.
It'll save you a small bit of overhead.
Configuring the session engineLink to this heading
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.
Using database-backed sessionsLink to this heading
If you want to use a database-backed session, you need to add
'django.contrib.sessions' to your INSTALLED_APPS setting.
Once you have configured your installation, run manage.py migrate
to install the single database table that stores session data.
Using cached sessionsLink to this heading
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.
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.
Once your cache is configured, you've got two choices for how to store data in the cache:
Set
SESSION_ENGINEto"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.For persistent, cached data, set
SESSION_ENGINEto"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.
Both session stores are quite fast, but the simple cache is faster because it
disregards persistence. In most cases, the cached_db backend will be fast
enough, but if you need that last bit of performance, and are willing to let
session data be expunged from time to time, the cache backend is for you.
If you use the cached_db session backend, you also need to follow the
configuration instructions for the using database-backed sessions.
Using file-based sessionsLink to this heading
To use file-based sessions, set the SESSION_ENGINE setting to
"django.contrib.sessions.backends.file".
You might also want to set the SESSION_FILE_PATH setting (which
defaults to output from tempfile.gettempdir(), most likely /tmp) to
control where Django stores session files. Be sure to check that your Web
server has permissions to read and write to this location.
Using sessions in viewsLink to this heading
When SessionMiddleware is activated, each HttpRequest
object -- the first argument to any Django view function -- will have a
session attribute, which is a dictionary-like object.
You can read it and write to request.session at any point in your view.
You can edit it multiple times.
- class backends.base.SessionBaseLink to this definition
This is the base class for all session objects. It has the following standard dictionary methods:
- __getitem__(key)Link to this definition
Example:
fav_color = request.session['fav_color']
- __setitem__(key, value)Link to this definition
Example:
request.session['fav_color'] = 'blue'
- __delitem__(key)Link to this definition
Example:
del request.session['fav_color']. This raisesKeyErrorif the givenkeyisn't already in the session.
- __contains__(key)Link to this definition
Example:
'fav_color' in request.session
- get(key, default=None)Link to this definition
Example:
fav_color = request.session.get('fav_color', 'red')
- pop(key, default=__not_given)Link to this definition
Example:
fav_color = request.session.pop('fav_color', 'blue')
- keys()Link to this definition
- items()Link to this definition
- setdefault()Link to this definition
- clear()Link to this definition
It also has these methods:
- flush()Link to this definition
Deletes the current session data from the session and deletes 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).
- set_test_cookie()Link to this definition
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.
- test_cookie_worked()Link to this definition
Returns either
TrueorFalse, depending on whether the user's browser accepted the test cookie. Due to the way cookies work, you'll have to callset_test_cookie()on a previous, separate page request. See Setting test cookies below for more information.
- delete_test_cookie()Link to this definition
Deletes the test cookie. Use this to clean up after yourself.
- set_expiry(value)Link to this definition
Sets the expiration time for the session. You can pass a number of different values:
If
valueis an integer, the session will expire after that many seconds of inactivity. For example, callingrequest.session.set_expiry(300)would make the session expire in 5 minutes.If
valueis adatetimeortimedeltaobject, the session will expire at that specific date/time. Note thatdatetimeandtimedeltavalues are only serializable if you are using thePickleSerializer.If
valueis0, the user's session cookie will expire when the user's Web browser is closed.If
valueisNone, 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()Link to this definition
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 adatetimeobject. Defaults to the current time.expiry: expiry information for the session, as adatetimeobject, anint(in seconds), orNone. Defaults to the value stored in the session byset_expiry(), if there is one, orNone.
- get_expiry_date()Link to this definition
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_AGEseconds from now.This function accepts the same keyword arguments as
get_expiry_age().
- get_expire_at_browser_close()Link to this definition
Returns either
TrueorFalse, depending on whether the user's session cookie will expire when the user's Web browser is closed.
- clear_expired()Link to this definition
Removes expired sessions from the session store. This class method is called by
clearsessions.
- cycle_key()Link to this definition
Creates a new session key while retaining the current session data.
django.contrib.auth.login()calls this method to mitigate against session fixation.
Session serializationLink to this heading
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.
Bundled serializersLink to this heading
- class serializers.JSONSerializerLink to this definition
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.sessionwon'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 raisesUnicodeDecodeError), can't be stored.See the Write your own serializer section for more details on limitations of JSON serialization.
- class serializers.PickleSerializerLink to this definition
Supports arbitrary Python objects, but, as described above, can lead to a remote code execution vulnerability if
SECRET_KEYbecomes known by an attacker.
Write your own serializerLink to this heading
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
datetimes).
Your serializer class must implement two methods,
dumps(self, obj) and loads(self, data), to serialize and deserialize
the dictionary of session data, respectively.
Session object guidelinesLink to this heading
Use normal Python strings as dictionary keys on
request.session. This is more of a convention than a hard-and-fast rule.Session dictionary keys that begin with an underscore are reserved for internal use by Django.
Don't override
request.sessionwith a new object, and don't access or set its attributes. Use it like a Python dictionary.
示例Link to this heading
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.
Using sessions out of viewsLink to this heading
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}
When sessions are savedLink to this heading
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.
Browser-length sessions vs. persistent sessionsLink to this heading
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.
Clearing the session storeLink to this heading
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.
SettingsLink to this heading
A few Django settings give you control over session behavior:
Session securityLink to this heading
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.
Technical detailsLink to this heading
The session dictionary accepts any
jsonserializable value when usingJSONSerializeror any picklable Python object when usingPickleSerializer. See thepicklemodule for more information.Session data is stored in a database table named
django_session.Django only sends a cookie if it needs to. If you don't set any session data, it won't send a session cookie.
The SessionStore objectLink to this heading
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()
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).
Extending database-backed session enginesLink to this heading
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.
- class base_session.AbstractBaseSessionLink to this definition
抽象基本会话模型。
- session_keyLink to this definition
主键。字段本身可能包含多达40个字符。当前实现生成一个32个字符的字符串(一个随机的数字序列和小写的ascii字母)。
- session_dataLink to this definition
包含编码和序列化会话字典的字符串。
- expire_dateLink to this definition
指定会话何时到期的日期时间。
但是,过期的会话对用户不可用,但在运行
clearsessions管理命令之前,它们仍可能存储在数据库中。
- classmethod get_session_store_class()Link to this definition
返回要与此会话模型一起使用的会话存储类。
- get_decoded()Link to this definition
返回解码的会话数据。
解码由会话存储类执行。
还可以通过子类 BaseSessionManager 自定义模型管理器。
- class base_session.BaseSessionManagerLink to this definition
- encode(session_dict)Link to this definition
返回序列化并编码为字符串的给定会话字典。
编码由绑定到模型类的会话存储类执行。
- save(session_key, session_dict, expire_date)Link to this definition
为提供的会话密钥保存会话数据,或在数据为空时删除会话。
通过重写以下描述的方法和属性,实现了 SessionStore 类的定制:
- class backends.db.SessionStoreLink to this definition
实现数据库支持的会话存储。
- classmethod get_model_class()Link to this definition
如果需要的话,重写此方法以返回自定义会话模型。
- create_model_instance(data)Link to this definition
返回会话模型对象的新实例,该实例表示当前会话状态。
重写此方法提供了在将会话模型数据保存到数据库之前修改它的能力。
- class backends.cached_db.SessionStoreLink to this definition
实现缓存数据库支持的会话存储。
- cache_key_prefixLink to this definition
添加到会话键中以生成缓存键字符串的前缀。
例如Link to this heading
下面的示例显示了一个自定义数据库支持的会话引擎,它包括一个用于存储帐户id的附加数据库列(从而提供了一个选项,用于查询数据库中帐户的所有活动会话):
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
如果要从Django的内置` cached_db` 会话存储迁移到基于``cached_db`` 的自定义存储,则应重写缓存键前缀,以防止名称空间冲突:
class SessionStore(CachedDBStore):
cache_key_prefix = 'mysessions.custom_cached_db_backend'
# ...
URL中的会话IDLink to this heading
Django会话框架完全是基于cookie的。 正如PHP所做的那样,它不会回退到将会话ID放置在URL中作为最后的手段。 这是一个有意设计的决定。 这种行为不仅使URL变得很难看,而且使您的站点容易受到会话ID的盗用。