Django中的cookie與session操作


添加cookie:

def login(req):
    if req.method=="POST":
        uf = UserInfoForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data["username"]
            password = uf.cleaned_data["password"]
            print username,password
            users = UserInfo.objects.filter(username=username,password=password)
            if users:
                response = HttpResponseRedirect("/index/")
                response.set_cookie("username",username,3600)
                return response
            else:
                return HttpResponseRedirect("/login")
            # return HttpResponseRedirect()
    else:
        uf = UserInfoForm()
    return render_to_response("login.html",{"uf":uf})

獲得cookie:

def index(req):
    username = req.COOKIES.get("username","")return render_to_response("index.html",{"username":username})

刪除cookie:

    Response.delete_cookie("username")

添加session:

def sesion(req):
    if req.method == "POST":
        uf = UserInfoForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data["username"]
            req.session["username"] = username
            return HttpResponseRedirect("/index/")
    else:
        uf = UserInfoForm()
    return render_to_response("LoadFile.html",{"uf":uf})

獲取session:

def index(req):
    username = req.session.get("username","")
    return render_to_response("index.html",{"username":username})

刪除session:

del req.session['username']


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM