Django点滴(二)---会话

本文介绍如何在Django中使用会话(Session)管理用户状态,包括配置中间件、选择存储引擎、在视图中操作会话对象等。还提供了示例代码说明登录、发表评论及登出等功能的实现。

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

会话(Session)用来在服务器端保存单个用户的会话状态,一般用于登录以后。会话ID可以通过cookie来传递给客户端,用于识别当前登录的用户。

参考:https://docs.djangoproject.com/en/dev/topics/http/sessions/


开启Session中间件

在settings.py中   MIDDLEWARE_CLASSES 加入 'django.contrib.sessions.middleware.SessionMiddleware'
(默认已经有了)


Session引擎

Django默认会使用数据库保存会话状态。此外,还可以设置 SESSION_ENGINE  选择使用基于缓存、文件、cookie等方式。
强烈建议将 SESSION_COOKIE_HTTPONLY置为True,防止恶意脚本读取到SessionID进而伪造跨站攻击。


在View中操作Session对象

Session对象定义在 backends.base. SessionBase类中。基本用法如下:

fav_color = request.session['fav_color']
request.session['fav_color'] = 'blue'
del request.session['fav_color']
'fav_color' in request.session
fav_color = request.session.get('fav_color', default='red')
fav_color = request.session.pop('fav_color')
request.session.set_expiry(300)



例如,先登录,新建会话

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

然后发表评论,检测会话判断是否已登录

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!')


最后登出,清除会话

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

测试客户端是否支持cookie

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')


Django will only save session when the value under a key has been modified. When you write:

request.session['array'] = []

it means that the value is a reference to your array. Appending items to the array will not modify the value (the reference to array), thus django sees no reason to save the session.

There are 2 ways of fixing this:
1) Tell django to explicitly save the session:
request.session.modified = True
2) set the SESSION_SAVE_EVERY_REQUEST setting to True. Django will then save the session to the database on every single request



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值