Django中session的使用

本文详细介绍了如何在Django中启用会话功能、配置会话存储引擎、使用会话在视图中操作数据以及如何在不同场景下选择合适的会话存储方式。包括文件、数据库、缓存和Cookie等存储机制的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

How to use sessions

原文地址: https://docs.djangoproject.com/en/dev/topics/http/sessions/

Django provides full support for anonymous sessions. The session frameworklets you store and retrieve arbitrary data on a per-site-visitor basis. Itstores data on the server side and abstracts the sending and receiving ofcookies. Cookies contain a session ID – not the data itself (unless you’reusing the cookie based backend).

Enabling sessions

Sessions are implemented via a piece of middleware.

To enable session functionality, do the following:

  • Edit the MIDDLEWARE_CLASSES setting and make sureit contains 'django.contrib.sessions.middleware.SessionMiddleware'.The default settings.py created by django-admin.py startprojecthas SessionMiddleware activated.

If you don’t want to use sessions, you might as well remove theSessionMiddleware line from MIDDLEWARE_CLASSES and'django.contrib.sessions' from your INSTALLED_APPS.It’ll save you a small bit of overhead.

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 syncdbto 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.

Warning

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.

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.

Changed in Django 1.5: The SESSION_CACHE_ALIAS setting was added.

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 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.

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)

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 regenerate thesession key value that is sent back to the user in the cookie. This isused if you want to ensure that the previous session data can’t beaccessed 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.

set_expiry( 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.
  • 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:

  • modification: last modification of the session, as adatetime object. Defaults to the current time.
  • expiry: expiry information for the session, as adatetime object, an int() (in seconds), orNone. Defaults to the value stored in the session byset_expiry(), if there is one, or None.
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 argumets 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.

SessionBase. clear_expired()
New in Django 1.5.

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

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.

Examples

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:

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 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:

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_to_response('foo/login_form.html')

Using sessions out of views

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

>>> from django.contrib.sessions.backends.db import SessionStore
>>> import datetime
>>> s = SessionStore()
>>> s['last_login'] = datetime.datetime(2005, 8, 20, 13, 35, 10)
>>> s.save()
>>> s.session_key
'2b1189a188b44ad18c35e113ac6ceead'

>>> s = SessionStore(session_key='2b1189a188b44ad18c35e113ac6ceead')
>>> s['last_login']
datetime.datetime(2005, 8, 20, 13, 35, 0)

In order to prevent session fixation attacks, sessions keys that don’t existare regenerated:

>>> from django.contrib.sessions.backends.db import SessionStore
>>> s = SessionStore(session_key='no-such-session-here')
>>> s.save()
>>> s.session_key
'ff882814010ccbc3c870523934fee5a2'

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:

>>> 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 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:

# 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 objectexplicitly that it has been modified by setting the modified attribute onthe session object:

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.

Changed in Django 1.5: 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 closeshis or her browser. Use this if you want people to have to log in every timethey open 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.

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 django_session 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.

Technical details

  • The session dictionary should accept any pickleable Python object. Seethe pickle 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.

Session IDs in URLs

The Django sessions framework is entirely, and solely, cookie-based. It doesnot 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 URLsugly, it makes your site vulnerable to session-ID theft via the “Referer”header.


### Django使用 Session 保持会话的指南 在 Django 中,Session 是一种强大的工具,用于在用户的多次请求之间保存状态信息。以下是关于如何配置和使用 Django Session 的详细介绍。 #### 配置 Session 功能 为了使 Django 支持 Session 功能,需要确保以下两项已正确配置: 1. **`MIDDLEWARE` 设置** 在 `settings.py` 文件中的 `MIDDLEWARE` 列表中添加 `'django.contrib.sessions.middleware.SessionMiddleware'`,这是启用 Session 功能的关键中间件[^1]。 2. **`INSTALLED_APPS` 设置** 同样,在 `settings.py` 文件中的 `INSTALLED_APPS` 列表中添加 `'django.contrib.sessions'` 应用程序。该应用程序提供了必要的数据库模型和其他支持功能来管理 Session 数据[^3]。 完成上述两步后,Django 就可以正常处理 Session 请求了。 --- #### 存储与读取 Session 数据 一旦启用了 Session 功能,就可以通过 `request.session` 对象轻松存储和检索数据。下面是一个简单的例子,展示了如何操作 Session 数据: ```python from django.http import HttpResponse def set_session(request): request.session['key'] = 'value' return HttpResponse('Session 已设置') def get_session(request): value = request.session.get('key', '默认值') return HttpResponse(f'Session 值为: {value}') ``` - 上述代码片段演示了如何向 Session 添加键值对 (`set_session`) 并从中获取值 (`get_session`)。 - 如果指定的键不存在,则可以通过 `.get()` 方法提供一个默认返回值[^4]。 --- #### 删除 Session 数据 如果不再需要某些 Session 数据,可以直接将其删除。例如: ```python def delete_session(request): if 'key' in request.session: del request.session['key'] return HttpResponse('Session 被成功删除') else: return HttpResponse('没有找到对应的 Session 键') ``` 这段代码检查是否存在名为 `'key'` 的 Session 条目,并在存在的情况下将其移除。 --- #### 自定义 Session 行为 除了基本的操作外,还可以自定义一些高级行为,例如调整超时时间或强制清除过期的 Session 记录。 1. **设置全局超时时间** 可以通过修改 `SESSION_COOKIE_AGE` 参数来自定义整个项目的 Session 过期时间(单位为秒)。例如: ```python SESSION_COOKIE_AGE = 1209600 # 默认两周 (1209600 秒) ``` 2. **单个 Session 的个性化超时** 若要针对某个特定用户设定不同的超时策略,可以在视图函数中调用 `set_expiry()` 方法: ```python def custom_timeout(request): request.session.set_expiry(3600) # 半小时后失效 return HttpResponse('设置了个性化的 Session 超时时间') ``` 3. **集成安全扩展** 若希望进一步增强安全性,可考虑引入第三方库如 `django-session-security`。它允许开发者更精细地控制用户会话的安全性,例如通过设置警告时间和自动登出时间实现更高的防护水平[^2]。 --- #### 注意事项 - 默认情况下,Django 使用数据库作为 Session 的存储后端。这意味着每次写入或读取 Session 数据都会涉及一次数据库查询。 - 如果性能成为瓶颈,可以选择其他存储方式,例如缓存(Redis 或 Memcached),只需更改 `SESSION_ENGINE` 和相关参数即可[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值