django装饰器使用案例-用户认证
urls.py
from django.conf.urls import url
from django.contrib import admin
from app1 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
url(r'^index/', views.index),
url(r'^home/', views.Home.as_view()),
]
views.py
from django.shortcuts import render, HttpResponse, redirect
from django.views import View
# Create your views here.
# 认证装饰器,带有不同认证方式
def auth(auth_type):
def warpper(func):
def inner(request, *args, **kwargs):
if auth_type == "ldap":
# ladp auth
user_cookie = request.COOKIES.get("username1")
if not user_cookie:
return redirect('/login/')
auth_result = func(request, *args, **kwargs)
return auth_result
elif auth_type == 'local':
# local auth
user_cookie = request.COOKIES.get("username1")
if not user_cookie:
return redirect("/login/")
auth_result = func(request, *args, **kwargs)
return auth_result
return inner
return warpper
- FBV添加认证方式
def login(request):
if request.method == "GET":
return render(request, 'login.html')
elif request.method == "POST":
user = request.POST.get('name')
pwd = request.POST.get('pass')
print(user, pwd)
if user == '1' and pwd == '1':
response = redirect("/index/")
response.set_signed_cookie("username1", user, salt='cookie_salt')
return response
else:
return render(request, 'login.html')
else:
return render(request, 'login.html')
@auth(auth_type="ldap")
def index(request):
if request.method == "GET":
try:
current_user = request.get_signed_cookie("username1", salt="cookie_salt", max_age=10)
except Exception as e:
current_user = None
if current_user:
return render(request, 'index.html', {'current_user': current_user})
else:
return redirect("/login/")
elif request.method == "POST":
pass
- CBV添加认证方式
from django.utils.decorators import method_decorator
@method_decorator(auth(auth_type='local'), name='dispatch')
class Home(View):
def get(self, request):
try:
current_user = request.get_signed_cookie("username1", salt="cookie_salt")
except Exception as e:
current_user = None
return render(request, 'home.html', {'current_user': current_user})
def post(self, request):
pass