Django Session不够用

时间:2012-07-21 10:01:48

标签: django session localhost

当我在django 1.4中打开会话时,一切都很好。如果我使用某些表单流程重定向我的页面,我可以阅读我的会话

示例:

<form id="processForm" action="http://localhost:8000" method="post">{% csrf_token %} 
   <input type="submit" value="Search"></input>
</form> 

我在localhost:8000和memcached工作。问题是,当我打开一个会话后,如果我在浏览器上搜索localhost:8000,我就无法阅读会话,就像它永远不会退出一样。

代码:

views.py

def search(request):     
    c = {}
    c.update(csrf(request))
    if request.session.get('name'):
        c.update({ 'hellomsg' : 'Hello:' + request.session["name"] })
    else:
        c.update({ 'hellomsg' : 'Hello: Guest' })        
    if request.method == 'POST':
        if request.POST['q']:
            if not request.POST['q'] == "false":                
                c.update({ 'output' : request.POST['q'] })
    return render_to_response("form.html", c, context_instance= RequestContext(request))

def open_session(request):
    c = {}    
    c.update(csrf(request))
    if not request.session.get('name'):
        if request.POST['nametxt']:
            request.session['name'] = request.POST['nametxt']
            c.update({ 'hellomsg' : 'Hello:' + request.POST['nametxt'] })
        else:
            c.update({ 'hellomsg' : 'Error...'})
    else:
        c.update({ 'hellomsg' : 'You're already logged in...'})
    return render_to_response("form.html", c, context_instance= RequestContext(request))

def close_session(request):
    c = {}
    c.update(csrf(request))
    if request.session.get('name'):
        try:
            del request.session['name']
            c.update({ 'hellomsg' : 'logged out...'})
        except KeyError:
            pass
    else:
        c.update({ 'hellomsg' : 'Error'})        
    return render_to_response("form.html", c, context_instance= RequestContext(request))  

urls.py

urlpatterns = patterns('',
    ('^$', search),
    ('^session/$', open_session),
    ('^csession/$', close_session),
)   

1 个答案:

答案 0 :(得分:2)

会话在Django中自动创建。请参阅this页。

要阅读或写入会话,您可以执行request.session['someting']