cookie/session(过时的写法)

cookie存在客户端的浏览器中,不太安全,容易被窃取,,session被存在服务器中(类似于字典中的value,),服务器会给浏览器返回这个value的key值,下次进来直接根据key取value.....
from django.shortcuts import render,HttpResponse,redirect
from app01 import models
# Create your views here.

def login(request):
    if request.method=="POST":
        username = request.POST.get("user")     #获取表单数据
        password = request.POST.get("pwd")
        print(username,'===========',password)

        ret = models.UserInfo.objects.filter(username=username,password=password)
        #查找数据表,找出获取到的表单数据在数据表里的数据
        if ret:       #如果获取到了就设置cookie
            # obj = redirect("/home/")
            # obj.set_cookie("is_login",True,20)      # 设置cookie,key  value  以及他的超时时间,超过时间cookie失效
            # obj.set_cookie("username",username)
            # return obj
            
            # 下边是基于session的验证     ↓cookie的设置
            request.session["IS_LOGON"] = True
            request.session["USER"] = username
            return redirect("/home/")

        else:                                       #本来验证错误应该重定向到验证页面,但是为了方便测试,返回字符串
            return redirect("/login/")
    return render(request,"login.html")

def home(request):
    # is_login = request.COOKIES.get("is_login",None)         #这里验证是否获取到cookie
    # if is_login:
    #     # username = request.COOKIES.get("username")
    #     username = request.POST.get("username")
    #     return render(request,"home.html",locals())

    # 下边是session的获取
    ret = request.session.get("IS_LOGON",None)
    if ret:
        username = request.session.get("USER")
        return render(request,"home.html",locals())

    else:
        return redirect("/login")



def add(request):
    is_login = request.COOKIES.get("is_login",None)
    if is_login:
        return HttpResponse("登录成功")
    else:
        return redirect("/login")
views视图
"""Cookie URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.conf.urls import url, include
    2. Add a URL to urlpatterns:  url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/',views.login),
    url(r'^home/',views.home),
    url(r'^add/',views.add)

]
url配置

下边就开始用封装好的模块写,,底层实现原理就是这种比较“过时的”,django只是给了我们一个接口,方便使用,不逼自己写太多的重复代码

posted @ 2017-11-01 14:55  一石数字欠我15w!!!  阅读(530)  评论(0编辑  收藏  举报