如何使用会话

Django 是支持匿名会话的。会话框架允许您基于每个站点访问者存储和检索任意数据。它在服务器端存储数据并提供cookie的发送和接收。Cookie包含会话ID - 而不是数据本身(除非您使用基于cookie的后端)。

打开会话

会话通过配置一个中间件实现的

为了打开会话,需要做下面的操作

  • 编辑设置中的 MIDDLEWARE,并确保他包含了 'django.contrib.sessions.middleware.SessionMiddleware'。通过 django-admin startproject 创建的默认 settings.py 文件是已经打开了 SessionMiddleware 这项设置的。如果你不想使用会话功能,你可以从配置的 MIDDLEWARE 中删除 `SessionMiddleware,并且从 INSTALLED_APPS 中删除 'django.contrib.sessions'。它将会为您节省一点开销。

Configuring the session engine

By default, Django stores sessions in your database (using the modeldjango.contrib.sessions.models.Session). Though this is convenient, insome setups it's faster to store session data elsewhere, so Django can beconfigured to store session data on your filesystem or in your cache.

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.

Once you have configured your installation, run manage.py migrateto install the single database table that stores session data.

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 makesure you've configured your cache; see the cache documentation for details.

警告

You should only use cache-based sessions if you're using the Memcachedcache backend. The local-memory cache backend doesn't retain data longenough to be a good choice, and it'll be faster to use file or databasesessions directly instead of sending everything through the file ordatabase cache backends. Additionally, the local-memory cache backend isNOT multi-process safe, therefore probably not a good choice for productionenvironments.

If you have multiple caches defined in CACHES, Django will use thedefault cache. To use another cache, set SESSION_CACHE_ALIAS to thename of that cache.

Once your cache is configured, you've got two choices for how to store data inthe cache:

  • Set SESSION_ENGINE to"django.contrib.sessions.backends.cache" for a simple caching sessionstore. Session data will be stored directly in your cache. However, sessiondata may not be persistent: cached data can be evicted if the cache fillsup or if the cache server is restarted.
  • For persistent, cached data, set SESSION_ENGINE to"django.contrib.sessions.backends.cached_db". This uses awrite-through cache — every write to the cache will also be written tothe database. Session reads only use the database if the data is notalready in the cache.Both session stores are quite fast, but the simple cache is faster because itdisregards persistence. In most cases, the cached_db backend will be fastenough, but if you need that last bit of performance, and are willing to letsession 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 theconfiguration instructions for the using database-backed sessions.

Using file-based sessions

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 (whichdefaults to output from tempfile.gettempdir(), most likely /tmp) tocontrol where Django stores session files. Be sure to check that your Webserver has permissions to read and write to this location.

To use cookies-based sessions, set the SESSION_ENGINE setting to"django.contrib.sessions.backends.signed_cookies". The session data will bestored using Django's tools for cryptographic signingand the SECRET_KEY setting.

注解

It's recommended to leave the SESSION_COOKIE_HTTPONLY settingon True to prevent access to the stored data from JavaScript.

警告

If the SECRET_KEY is not kept secret and you are using thePickleSerializer, this canlead to arbitrary remote code execution.

An attacker in possession of the SECRET_KEY can not onlygenerate falsified session data, which your site will trust, but alsoremotely execute arbitrary code, as the data is serialized using pickle.

If you use cookie-based sessions, pay extra care that your secret key isalways kept completely secret, for any system which might be remotelyaccessible.

The session data is signed but not encrypted

When using the cookies backend the session data can be read by the client.

A MAC (Message Authentication Code) is used to protect the data againstchanges by the client, so that the session data will be invalidated when beingtampered with. The same invalidation happens if the client storing thecookie (e.g. your user's browser) can't store all of the session cookie anddrops data. Even though Django compresses the data, it's still entirelypossible to exceed the common limit of 4096 bytes per cookie.

No freshness guarantee

Note also that while the MAC can guarantee the authenticity of the data(that it was generated by your site, and not someone else), and theintegrity of the data (that it is all there and correct), it cannotguarantee freshness i.e. that you are being sent back the last thing yousent to the client. This means that for some uses of session data, thecookie backend might open you up to replay attacks. Unlike other sessionbackends which keep a server-side record of each session and invalidate itwhen a user logs out, cookie-based sessions are not invalidated when a userlogs out. Thus if an attacker steals a user's cookie, they can use thatcookie to login as that user even if the user logs out. Cookies will onlybe detected as 'stale' if they are older than yourSESSION_COOKIE_AGE.

Performance

Finally, the size of a cookie can have an impact on the speed of your site.

Using sessions in views

When SessionMiddleware is activated, each HttpRequestobject — the first argument to any Django view function — will have asession 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.SessionBase
  • This is the base class for all session objects. It has the followingstandard dictionary methods:

    • 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 KeyErrorif 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, default=__not_given)

    • Example: fav_color = request.session.pop('fav_color', 'blue')

    • keys()

    • items()
    • setdefault()
    • clear()
    • It also has these methods:

    • flush()

    • Deletes the current session data from the session and deletes the sessioncookie. This is used if you want to ensure that the previous session datacan't be accessed again from the user's browser (for example, thedjango.contrib.auth.logout() function calls it).

    • set_test_cookie()

    • Sets a test cookie to determine whether the user's browser supportscookies. Due to the way cookies work, you won't be able to test thisuntil the user's next page request. See Setting test cookies below formore information.

    • test_cookie_worked()

    • Returns either True or False, depending on whether the user'sbrowser accepted the test cookie. Due to the way cookies work, you'llhave to call set_test_cookie() on a previous, separate page request.See Setting test cookies below for more information.

    • delete_test_cookie()

    • Deletes the test cookie. Use this to clean up after yourself.

    • setexpiry(_value)

    • Sets the expiration time for the session. You can pass a number ofdifferent values:

      • If value is an integer, the session will expire after thatmany seconds of inactivity. For example, callingrequest.session.set_expiry(300) would make the session expirein 5 minutes.
      • If value is a datetime or timedelta object, thesession will expire at that specific date/time. Note that datetimeand timedelta values are only serializable if you are using thePickleSerializer.
      • If value is 0, the user's session cookie will expirewhen the user's Web browser is closed.
      • If value is None, the session reverts to using the globalsession expiry policy.Reading a session is not considered activity for expirationpurposes. Session expiration is computed from the last time thesession was modified.
    • get_expiry_age()

    • Returns the number of seconds until this session expires. For sessionswith no custom expiration (or those set to expire at browser close), thiswill equal SESSION_COOKIE_AGE.

This function accepts two optional keyword arguments:

  1. - <code>modification</code>: last modification of the session, as a[<code>datetime</code>](https://docs.python.org/3/library/datetime.html#datetime.datetime) object. Defaults to the current time.
  2. - <code>expiry</code>: expiry information for the session, as a[<code>datetime</code>](https://docs.python.org/3/library/datetime.html#datetime.datetime) object, an [<code>int</code>](https://docs.python.org/3/library/functions.html#int) (in seconds), or<code>None</code>. Defaults to the value stored in the session by[<code>set_expiry()</code>]($1c3fd5f297edc7f2.md#django.contrib.sessions.backends.base.SessionBase.set_expiry), if there is one, or <code>None</code>.
  • get_expiry_date()
  • Returns the date this session will expire. For sessions with no customexpiration (or those set to expire at browser close), this will equal thedate 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'ssession cookie will expire when the user's Web browser is closed.

  • clear_expired()

  • Removes expired sessions from the session store. This class method iscalled by clearsessions.

  • cycle_key()

  • Creates a new session key while retaining the current session data.django.contrib.auth.login() calls this method to mitigate againstsession fixation.

Session serialization

By default, Django serializes session data using JSON. You can use theSESSION_SERIALIZER setting to customize the session serializationformat. Even with the caveats described in Write your own serializer, we highlyrecommend sticking with JSON serialization especially if you are using thecookie backend.

For example, here's an attack scenario if you use pickle to serializesession 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 andeasily available on the internet. Although the cookie session storage signs thecookie-stored data to prevent tampering, a SECRET_KEY leakimmediately escalates to a remote code execution vulnerability.

Bundled serializers

  • class serializers.JSONSerializer
  • A wrapper around the JSON serializer from django.core.signing. Canonly serialize basic data types.

In addition, as JSON supports only string keys, note that using non-stringkeys in request.session won't work as expected:

  1. >>> # initial assignment
  2. >>> request.session[0] = 'bar'
  3. >>> # subsequent requests following serialization & deserialization
  4. >>> # of session data
  5. >>> request.session[0] # KeyError
  6. >>> request.session['0']
  7. '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 limitationsof JSON serialization.

  • class serializers.PickleSerializer
  • Supports arbitrary Python objects, but, as described above, can lead to aremote code execution vulnerability if SECRET_KEY becomes knownby an attacker.

Write your own serializer

Note that unlike PickleSerializer,the JSONSerializer cannot handlearbitrary Python data types. As is often the case, there is a trade-off betweenconvenience and security. If you wish to store more advanced data typesincluding datetime and Decimal in JSON backed sessions, you will needto write a custom serializer (or convert such values to a JSON serializableobject before storing them in request.session). While serializing thesevalues is fairly straightforward(DjangoJSONEncoder may be helpful),writing a decoder that can reliably get back the same thing that you put in ismore fragile. For example, you run the risk of returning a datetime thatwas actually a string that just happened to be in the same format chosen fordatetimes).

Your serializer class must implement two methods,dumps(self, obj) and loads(self, data), to serialize and deserializethe dictionary of session data, respectively.

Session object guidelines

  • Use normal Python strings as dictionary keys on request.session. Thisis more of a convention than a hard-and-fast rule.
  • Session dictionary keys that begin with an underscore are reserved forinternal use by Django.
  • Don't override request.session with a new object, and don't access orset its attributes. Use it like a Python dictionary.

示例

This simplistic view sets a has_commented variable to True after a userposts a comment. It doesn't let a user post a comment more than once:

  1. def post_comment(request, new_comment):
  2. if request.session.get('has_commented', False):
  3. return HttpResponse("You've already commented.")
  4. c = comments.Comment(comment=new_comment)
  5. c.save()
  6. request.session['has_commented'] = True
  7. return HttpResponse('Thanks for your comment!')

This simplistic view logs in a "member" of the site:

  1. def login(request):
  2. m = Member.objects.get(username=request.POST['username'])
  3. if m.password == request.POST['password']:
  4. request.session['member_id'] = m.id
  5. return HttpResponse("You're logged in.")
  6. else:
  7. return HttpResponse("Your username and password didn't match.")

…And this one logs a member out, according to login() above:

  1. def logout(request):
  2. try:
  3. del request.session['member_id']
  4. except KeyError:
  5. pass
  6. return HttpResponse("You're logged out.")

The standard django.contrib.auth.logout() function actually does a bitmore than this to prevent inadvertent data leakage. It calls theflush() method of request.session.We are using this example as a demonstration of how to work with sessionobjects, not as a full logout() implementation.

Setting test cookies

As a convenience, Django provides an easy way to test whether the user'sbrowser accepts cookies. Just call theset_test_cookie() method ofrequest.session in a view, and calltest_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'tactually tell whether a browser accepted it until the browser's next request.

It's good practice to usedelete_test_cookie() to clean up afteryourself. Do this after you've verified that the test cookie worked.

Here's a typical usage example:

  1. from django.http import HttpResponse
  2. from django.shortcuts import render
  3.  
  4. def login(request):
  5. if request.method == 'POST':
  6. if request.session.test_cookie_worked():
  7. request.session.delete_test_cookie()
  8. return HttpResponse("You're logged in.")
  9. else:
  10. return HttpResponse("Please enable cookies and try again.")
  11. request.session.set_test_cookie()
  12. return render(request, 'foo/login_form.html')

Using sessions out of views

注解

The examples in this section import the SessionStore object directlyfrom the django.contrib.sessions.backends.db backend. In your own code,you should consider importing SessionStore from the session enginedesignated by SESSION_ENGINE, as below:

  1. >>> from importlib import import_module
  2. >>> from django.conf import settings
  3. >>> SessionStore = import_module(settings.SESSION_ENGINE).SessionStore

An API is available to manipulate session data outside of a view:

  1. >>> from django.contrib.sessions.backends.db import SessionStore
  2. >>> s = SessionStore()
  3. >>> # stored as seconds since epoch since datetimes are not serializable in JSON.
  4. >>> s['last_login'] = 1376587691
  5. >>> s.create()
  6. >>> s.session_key
  7. '2b1189a188b44ad18c35e113ac6ceead'
  8. >>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
  9. >>> s['last_login']
  10. 1376587691

SessionStore.create() is designed to create a new session (i.e. one notloaded from the session store and with session_key=None). save() isdesigned 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 ofgenerating 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, eachsession is just a normal Django model. The Session model is defined indjango/contrib/sessions/models.py. Because it's a normal model, you canaccess sessions using the normal Django database API:

  1. >>> from django.contrib.sessions.models import Session
  2. >>> s = Session.objects.get(pk='2b1189a188b44ad18c35e113ac6ceead')
  3. >>> s.expire_date
  4. datetime.datetime(2005, 8, 20, 13, 35, 12)

Note that you'll need to callget_decoded() to get the sessiondictionary. This is necessary because the dictionary is stored in an encodedformat:

  1. >>> s.session_data
  2. 'KGRwMQpTJ19hdXRoX3VzZXJfaWQnCnAyCkkxCnMuMTExY2ZjODI2Yj...'
  3. >>> s.get_decoded()
  4. {'user_id': 42}

When sessions are saved

By default, Django only saves to the session database when the session has beenmodified — that is if any of its dictionary values have been assigned ordeleted:

  1. # Session is modified.
  2. request.session['foo'] = 'bar'
  3.  
  4. # Session is modified.
  5. del request.session['foo']
  6.  
  7. # Session is modified.
  8. request.session['foo'] = {}
  9.  
  10. # Gotcha: Session is NOT modified, because this alters
  11. # request.session['foo'] instead of request.session.
  12. request.session['foo']['bar'] = 'baz'

In the last case of the above example, we can tell the session objectexplicitly that it has been modified by setting the modified attribute onthe session object:

  1. request.session.modified = True

To change this default behavior, set the SESSION_SAVE_EVERY_REQUESTsetting to True. When set to True, Django will save the session to thedatabase on every single request.

Note that the session cookie is only sent when a session has been created ormodified. If SESSION_SAVE_EVERY_REQUEST is True, the sessioncookie will be sent on every request.

Similarly, the expires part of a session cookie is updated each time thesession cookie is sent.

The session is not saved if the response's status code is 500.

Browser-length sessions vs. persistent sessions

You can control whether the session framework uses browser-length sessions vs.persistent sessions with the SESSION_EXPIRE_AT_BROWSER_CLOSEsetting.

By default, SESSION_EXPIRE_AT_BROWSER_CLOSE is set to False,which means session cookies will be stored in users' browsers for as long asSESSION_COOKIE_AGE. Use this if you don't want people to have tolog in every time they open a browser.

If SESSION_EXPIRE_AT_BROWSER_CLOSE is set to True, Django willuse browser-length cookies — cookies that expire as soon as the user closestheir browser. Use this if you want people to have to log in every time theyopen a browser.

This setting is a global default and can be overwritten at a per-session levelby explicitly calling the set_expiry() methodof request.session as described above in using sessions in views.

注解

Some browsers (Chrome, for example) provide settings that allow users tocontinue browsing sessions after closing and re-opening the browser. Insome cases, this can interfere with theSESSION_EXPIRE_AT_BROWSER_CLOSE setting and prevent sessionsfrom expiring on browser close. Please be aware of this while testingDjango applications which have theSESSION_EXPIRE_AT_BROWSER_CLOSE setting enabled.

Clearing the session store

As users create new sessions on your website, session data can accumulate inyour session store. If you're using the database backend, thedjango_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 djangosession databasetable. Django updates this row each time the session data changes. If the userlogs 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 aclean-up management command for this purpose: clearsessions. It'srecommended to call this command on a regular basis, for example as a dailycron job.

Note that the cache backend isn't vulnerable to this problem, because cachesautomatically delete stale data. Neither is the cookie backend, because thesession data is stored by the users' browsers.

Settings

A few Django settings give you control over sessionbehavior:

Session security

Subdomains within a site are able to set cookies on the client for the wholedomain. This makes session fixation possible if cookies are permitted fromsubdomains not controlled by trusted users.

For example, an attacker could log into good.example.com and get a validsession 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 permittedto set cookies on *.example.com. When you visit good.example.com,you'll be logged in as the attacker and might inadvertently enter yoursensitive personal data (e.g. credit card info) into the attacker's account.

Another possible attack would be if good.example.com sets itsSESSION_COOKIE_DOMAIN to "example.com" which would causesession cookies from that site to be sent to bad.example.com.

Technical details

  • The session dictionary accepts any json serializable value when usingJSONSerializer or anypicklable Python object when usingPickleSerializer. See thepickle module 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 sessiondata, it won't send a session cookie.

The SessionStore object

When working with sessions internally, Django uses a session store object fromthe corresponding session engine. By convention, the session store object classis named SessionStore and is located in the module designated bySESSION_ENGINE.

All SessionStore classes available in Django inherit fromSessionBase 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, youmay create a new class inheriting from SessionBase orany other existing SessionStore class.

Extending most of the session engines is quite straightforward, but doing sowith database-backed session engines generally requires some extra effort (seethe next section for details).

Extending database-backed session engines

Creating a custom database-backed session engine built upon those included inDjango (namely db and cached_db) may be done by inheritingAbstractBaseSession and either SessionStore class.

AbstractBaseSession and BaseSessionManager are importable fromdjango.contrib.sessions.base_session so that they can be imported withoutincluding django.contrib.sessions in INSTALLED_APPS.

  • class base_session.AbstractBaseSession
  • 抽象基本会话模型。

    • session_key
    • 主键。字段本身可能包含多达40个字符。当前实现生成一个32个字符的字符串(一个随机的数字序列和小写的ascii字母)。

    • session_data

    • 包含编码和序列化会话字典的字符串。

    • expire_date

    • 指定会话何时到期的日期时间。

但是,过期的会话对用户不可用,但在运行 clearsessions 管理命令之前,它们仍可能存储在数据库中。

  • classmethod get_session_store_class()
  • 返回要与此会话模型一起使用的会话存储类。

  • get_decoded()

  • 返回解码的会话数据。

解码由会话存储类执行。

还可以通过子类 BaseSessionManager 自定义模型管理器。

  • class base_session.BaseSessionManager
    • encode(session_dict)
    • 返回序列化并编码为字符串的给定会话字典。

编码由绑定到模型类的会话存储类执行。

  • save(session_key, session_dict, expire_date)
  • 为提供的会话密钥保存会话数据,或在数据为空时删除会话。

通过重写以下描述的方法和属性,实现了 SessionStore 类的定制:

  • class backends.db.SessionStore
  • 实现数据库支持的会话存储。

    • classmethod get_model_class()
    • 如果需要的话,重写此方法以返回自定义会话模型。

    • createmodel_instance(_data)

    • 返回会话模型对象的新实例,该实例表示当前会话状态。

重写此方法提供了在将会话模型数据保存到数据库之前修改它的能力。

  • class backends.cached_db.SessionStore
  • 实现缓存数据库支持的会话存储。

    • cache_key_prefix
    • 添加到会话键中以生成缓存键字符串的前缀。

例如

下面的示例显示了一个自定义数据库支持的会话引擎,它包括一个用于存储帐户id的附加数据库列(从而提供了一个选项,用于查询数据库中帐户的所有活动会话):

  1. from django.contrib.sessions.backends.db import SessionStore as DBStore
  2. from django.contrib.sessions.base_session import AbstractBaseSession
  3. from django.db import models
  4.  
  5. class CustomSession(AbstractBaseSession):
  6. account_id = models.IntegerField(null=True, db_index=True)
  7.  
  8. @classmethod
  9. def get_session_store_class(cls):
  10. return SessionStore
  11.  
  12. class SessionStore(DBStore):
  13. @classmethod
  14. def get_model_class(cls):
  15. return CustomSession
  16.  
  17. def create_model_instance(self, data):
  18. obj = super().create_model_instance(data)
  19. try:
  20. account_id = int(data.get('_auth_user_id'))
  21. except (ValueError, TypeError):
  22. account_id = None
  23. obj.account_id = account_id
  24. return obj

如果要从Django的内置_cached_db_ 会话存储迁移到基于cached_db 的自定义存储,则应重写缓存键前缀,以防止名称空间冲突:

  1. class SessionStore(CachedDBStore):
  2. cache_key_prefix = 'mysessions.custom_cached_db_backend'
  3.  
  4. # ...

URL中的会话ID

Django会话框架完全是基于cookie的。 正如PHP所做的那样,它不会回退到将会话ID放置在URL中作为最后的手段。 这是一个有意设计的决定。 这种行为不仅使URL变得很难看,而且使您的站点容易受到会话ID的盗用。