博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
FBV和CBV装饰器
阅读量:6966 次
发布时间:2019-06-27

本文共 2302 字,大约阅读时间需要 7 分钟。

FBV装饰器:

def cook(request):    err_msg=""    if request.method == "GET":        return render(request,'cookie.html')    if request.method == "POST":        username = request.POST.get('username')        p = request.POST.get('password')        dic = user_info.get(username)        print(dic)        if not dic:            err_msg="用户不存在"            return render(request,'cookie.html',{
'err_msg':err_msg}) if dic['pwd'] == int(p): res = redirect('/xiaoqing/cookie1') # res.set_cookie('username_cookie',username) #设置cookie 关闭浏览器失效 # res.set_cookie('username_cookie',username,max_age=10) 设置cookie失效时间 10秒过期 import datetime current_date=datetime.datetime.utcnow() change_date=current_date+datetime.timedelta(seconds=5) res.set_cookie('username_cookie',username,expires=change_date) #到哪个时间失效 # res.set_signed_cookie('username_cookie',username,salt='sdasdas') return res else: return render(request,'cookie.html')
cook函数set cookie
def auth(func):  #装饰器 cookie认证    def inner(request,*args,**kwargs):        v = request.COOKIES.get('username_cookie')        print(v)        if not v:            return redirect('/xiaoqing/cookie')        return func(request,*args,**kwargs)    return inner@authdef cook1(request):    #获取当前已经登录的用户    v=request.COOKIES.get('username_cookie')   #获取cookie    # 或者 v=request.COOKIES['username_cookie']  #获取cookie    # v=request.get_signed_cookie('username_cookie',salt='sdasdas')   #获取加密cookie    return render(request,'cookie1.html',{
'current_user':v,})

CBV装饰器

 

def auth(func): #装饰器    def inner(request,*args,**kwargs):        v = request.COOKIES.get('username_cookie')        print(v)        if not v:            return redirect('/xiaoqing/cookie')        return func(request,*args,**kwargs)    return innerfrom django import viewsfrom django.utils.decorators import method_decorator  #导入方法@method_decorator(auth,name='dispatch')  #类中全部方法做认证class Order(views.View):    # @method_decorator(auth)  #单独方法做认证    def get(self,request):        v=request.COOKIES.get('username_cookie')        return render(request,'cookie1.html',{
'current_user':v,}) def post(self,request): pass

 

转载于:https://www.cnblogs.com/sunhao96/p/8980476.html

你可能感兴趣的文章
Mac 10.12安装WebStorm
查看>>
Spring Cloud启动应用时指定IP或忽略某张网卡配置
查看>>
Jenkins配置MSBuild实现自动部署2(项目实践)
查看>>
kafka好文章
查看>>
IBM发布超强量子计算机,可处理50个量子位
查看>>
如何使用Bro IDS和Intel Critical Stack分析网络活动
查看>>
Memcached的Web管理工具MemAdmin(待实践)
查看>>
嵌入式学习难点 嵌入式软件学习
查看>>
11204 ASM 在线存储迁移。
查看>>
eclipse不会自动编译的问题解决
查看>>
linux netstat命令
查看>>
淘宝卖家遭恶退诈骗 阿里一年来协助警方抓获103人
查看>>
拥2180亿美元收入,苹果成全球最大IT企业
查看>>
数据库连接池的工作原理
查看>>
网络抓包工具wireshark and tcpdump 及其实现基于的libpcap
查看>>
市值410亿美元!VR内容在5年后将成下一座金矿
查看>>
easyui的combobox根据后台数据实现自动输入提示功能
查看>>
ASP.NET MVC WEB API必知必会知识点总结
查看>>
Test2 unit6
查看>>
sql注入<二>
查看>>