十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
urls.py
url(r'^admin/', admin.site.urls), url(r'^set_cookie/',views.set_cookie), url(r'^get_cookie/',views.get_cookie), url(r'^login/',views.login), url(r'^order/',views.order), url(r'^shopping/',views.shopping),
views.py
from django.shortcuts import render, HttpResponse, redirect # 测试的时候要记得清理缓存哦 # Create your views here. # 登录认证装饰器 def login_auth(func): def inner(request, *args, **kwargs): # 拿到之前访问的路径 url = request.get_full_path() is_login = request.COOKIES.get('is_login') if is_login: res = func(request, *args, **kwargs) return res else: return redirect('/login/?next=%s' %url) # return redirect('/login/') return inner # ------------------------ def set_cookie(request): obj = HttpResponse('ok') obj.set_cookie('name', 's_jun') return obj def get_cookie(request): print(type(request.COOKIES)) print(request.COOKIES) name = request.COOKIES.get('name') obj = HttpResponse("get_cookie") return obj # ------------------------------------------------------------- # 新的login,拿到之前访问的路径 # 访问/order/ (没有登录,并且删除cookie)页面的时候,会跳到/login/?next=/order/的页面,若是成功登录以后,变会跳到之前访问的路径.(例如:/order/) def login(request): if request.method == "GET": return render(request, 'login.html') else: next = request.GET.get('next') name = request.POST.get('name') pwd = request.POST.get('pwd') if name == 's_jun' and pwd == '123': if next: obj=redirect(next) else: obj=redirect('/shopping/') obj.set_cookie('is_login', True) # 设置cookie return obj else: return HttpResponse('用户名或密码错误') # 原来的login # def login(request): # if request.method == "GET": # return render(request, 'login.html') # else: # name = request.POST.get('name') # pwd = request.POST.get('pwd') # if name == 's_jun' and pwd == '123': # obj = HttpResponse('登录成功,写入cookie,请刷新页面后查看cookie,返回/order/或者/shopping/,页面查看登录结果') # obj.set_cookie('is_login', True) # 设置cookie # return obj # else: # return HttpResponse('用户名或密码错误') # ↑上login 函数与(http://127.0.0.1:8000/order,访问时,若没有登录的情况下,会自动跳转到/login/的页面中,只有登录了才可以看到 http://127.0.0.1:8000/order/的这个页面中(没有跳转到/login/的页面中) )order函数下↓ # 此是为了判断cookie是否存在,存在的话便会看到order的页面中 # 基于cookie 写了登录验证 # def order(request): # is_login = request.COOKIES.get('is_login') # 获取cookie # # 判断是否有cookie,获取到的话会看到"我是订单页面,我得登录才能看",获取不到会返回到/login/页面中 # if is_login: # return HttpResponse('我是订单页面,我得登录才能看') # else: # return redirect('/login/') # # # def shopping(request): # is_login = request.COOKIES.get('is_login') # 获取cookie # if is_login: # return HttpResponse('我是购物页面,我得登录才能看') # else: # return redirect('/login/') # 登录验证语法糖 @login_auth def order(request): return HttpResponse('我是订单页面,我得登录才能看') @login_auth def shopping(request): return HttpResponse('我是购物页面,我得登录才能看')