cookie实现用户登录验证

cookie实现用户登录验证

1,

INSTALLED_APPS中注册app03

2,在主程序中新建映射关系到app3的url中
1 from django.conf.urls import url,include#引入include模块
2 from django.contrib import admin
3 
4 urlpatterns = [
5     url(r'^admin/', admin.site.urls),
6     url(r'^a/', include("app1.urls")),
7     url(r'^b/', include("app2.urls")),
8     url(r'^c/', include("app3.urls")),
9 ]

3.视图函数

user_info = {
    'asd': {'pwd': "123123"},
    'qwe': {'pwd': "666123"},
}


def login(request):
    if request.method == "GET":
        return render(request, 'test3login.html')  # 用户请求方式为get时,返回test3login.html信息
    if request.method == "POST":  # 如果用户为post请求时,获取用户数据
        u = request.POST.get('username')
        p = request.POST.get('pwd')
        dic = user_info.get(u)

        if not dic:
            return render(request, 'test3login.html')
        if dic['pwd'] == p:
            res = redirect('/c/test3/')
            res.set_cookie('username111')
            # res.set_cookie('username111',u,max_age=10)
            # import datetime
            # current_date = datetime.datetime.utcnow()
            # current_date = current_date + datetime.timedelta(seconds=5)
            # res.set_cookie('username111',u,expires=current_date)
            res.set_cookie('username111', u)
            res.set_cookie('user_type', "f", httponly=True)
            return res
        else:
            return render(request, 'test3login.html')


def index(reqeust):
    # 获取当前已经登录的用户
    v = reqeust.COOKIES.get('username111')
    
    return render(reqeust,'index.html',{'current_user': v})

 4,test3login.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <form method="post" action="/c/test2/">
 9     <input type="text" name="username" placeholder="用户名">
10     <input type="password" name="pwd" placeholder="密码">
11     <input type="submit">
12 </form>
13 </body>
14 </html>

5,index.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <h1>欢迎登录:{{ current_user }}</h1>
 9 </body>
10 </html>

 

转载于:https://www.cnblogs.com/cerofang/p/8401672.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值