美文网首页
第十四章: 会话、用户和注册

第十四章: 会话、用户和注册

作者: Farewell_lpf | 来源:发表于2018-11-09 11:40 被阅读0次
    存取Cookie
    def show_color(request):
      if "favorite_color" in request.COOKIES:
        return HttpResponse(request.COOKIES['favorite_color'])      
    

    写cookie 需要使用HttpResponse对象的set_cookie()方法

    response=HttpResponse(request.GET["favorite_color"])
    response.set_cookie("favorite_color",request.GET["favorite_color"])
    return response
    

    response.set_cookie()传递参数控制cookie的行为

    • max_age cookie需要延续的时间
    • expires cookie失效的实际日期
    打开session

    通过一个中间件实现

    • 编辑MIDDLEWARE_CLASSES配置
      'django.contrib.sessions.middleware.SessionMiddleware'
    • 确认INSTALL_APPS 中有'django.contrib.sessions'(如果你是刚打开这个应用,别忘了运行 manage.py syncdb )
    视图中使用session
    #set a session
    request.session["fav_color"]="blue"
    #get a session
    fav_color=request.session["fav_color"]
    #clear a session
    del request.session["fav_color"]
    #ckeck if the session has a given key
    if "fav_color" in request.session:
    

    防止用户对此评论

    def post_comment(request):
      if request.session.get('has_commented',False):
          return HttpResponse("You have aleardy commented")
      ....
      request.session['has_commented']=True
    return HttpResponse("Thanks for your comment!")
    
    设置测试Cookie

    Dajngo提供一个简单的方法来测试用户的浏览器是否接收cookie。
    request.session.test_cookie_worked()
    request.session.set_test_cookie()

    def login(request):
    
        # If we submitted the form...
        if request.method == 'POST':
    
            # Check that the test cookie worked (we set it below):
            if request.session.test_cookie_worked():
    
                # The test cookie worked, so delete it.
                request.session.delete_test_cookie()
    
                # In practice, we'd need some logic to check username/password
                # here, but since this is an example...
                return HttpResponse("You're logged in.")
    
            # The test cookie failed, so display an error message. If this
            # were a real site, we'd want to display a friendlier message.
            else:
                return HttpResponse("Please enable cookies and try again.")
    
        # If we didn't post, send the test cookie along with the login form.
        request.session.set_test_cookie()
        return render_to_response('foo/login_form.html')
    
    用户与Authentication
    • 验证(用户名密码)

    相关文章

      网友评论

          本文标题:第十四章: 会话、用户和注册

          本文链接:https://www.haomeiwen.com/subject/vkzwxqtx.html