In the last chapter, we have implemented encryption, decryption and modification of passwords, this chapter describes the simulation Auth encapsulation login, exit, adorner, middleware, context function One, encapsulate login function
1, Guide package (using the second encryption mode of the module)
From models import Webusermodel
import configs
2, the method of encapsulation login
# Package Login Method
def front_login (request, email, password):
# Query user password based on mailbox
WebUser = WebUserModel.objects.filter ( Email=email). I
if webUser:
# Verify that the password entered by the user is correct result
= Webuser.check_password (password)
if Result:
# Saves the UID of the current user to Request.session
request.session[configs. Logined_key] = str (WEBUSER.UID) return
webUser
else: return
none
else: return
None
3, testing
# Test Login
def login (request):
email = ' aab@qq.com '
password = ' 123 ' Result
= Front_login (Request,email, Password)
print ' * ' *100
print result
print ' * ' *100
if result: return
render (request, ' login.html
Else: Return
httpresponse (U ' login fail ')
second, the exit package
1. Specific code
# Encapsulation Exit Method
def front_logout (request):
try:
del request.session[configs. Logined_key]
except Keyerror:
Pass
third, the registration of the adorner
An adorner is actually a function, an Cauchy-physics function that receives a function.
1, Guide Bag
Import configs
from django.shortcuts import redirect, reverse
2. Define an Adorner
# define a login adorner
def front_login_required (func):
def wrapper (request, *args, **kwargs):
# Obtain the UID uid that is stored at logon time from request
= Request.session.get (configs. Logined_key)
if UID: Return
func (Request, *args, **kwargs)
else:
# impersonate the auth adorner
url = reverse ( Configs. Front_login) + '? next= ' + request.path return
redirect (URL) return
wrapper
3. Use
From frontauth.decorators import front_login_required
@front_login_required
def index (request):
return render (Request, ' index.html ')
IV. Middleware
Middleware does some processing between request and view, and between view and response.
1. Define a middleware
From django.utils.deprecation import middlewaremixin from
models import webusermodel
import configs
# Define a front-end middleware
class Authfrontmiddleware (middlewaremixin):
# handle View->request
def process_request (self, Request):
# 1. Obtain UID from request to determine whether to log in
if Request.session.get (configs. Logined_key):
# 2. Determine if Front_user if not hasattr is already added to the current request
(request, ' Front_user '):
uid = Request.session.get (configs. Logined_key)
WebUser = WebUserModel.objects.filter (Pk=uid). (a)
setattr (Request, ' Front_user ', WebUser)
# processing View->response
# def process_response (self, Request,response):
# Pass
2, in the settings.py file registration
Middleware = [
...
] Frontauth.middlewares.AuthFrontMiddleWare ', # Register your own defined middleware
]
3, testing
def middlewares (Request):
if hasattr (Request, ' Front_user '):
print Request.front_user
return HttpResponse (U ' already has middleware front_user ')
else:
return HttpResponse (U ' no middleware front_user ')
Five, context processor
The context handler returns a dictionary (the other language is called the object, which is required)
1. Define a context
Import configs from
models import Webusermodel
def frontauth (Request):
# 1. Determine whether the user is logged in
uid = Request.session.get (configs. Logined_key)
If UID:
if hasattr (Request, ' Front_user '): return
{' Front_user ': Request.front_user}
else:
webUser = WebUserModel.objects.filter (Pk=uid). A () return
{' Front_user ': WebUser}
Else: return
{}
2, in the settings.py file registration
TEMPLATES = [
{
' backend ': ' django.template.backends.django.DjangoTemplates ', '
dirs ': [Os.path.join ( Base_dir, ' templates ')]
,
' app_dirs ': True,
' OPTIONS ': {
' context_processors ': [
...
'] Frontauth.contextProcessors.FrontAuth '
],
},
},
]
3, testing
Vi. summarizing and comparing middleware and context1, the same point is defined by the need to register in the settings.py file 2, the same point is that they're all kind of like defining a global variable, you can get 3 of the main differences throughout the project: The middleware is used in back-end code, and the context is used in the front-end template with 4, In the case of separation and development now, the context is a bit similar to the front-end local storage, in the actual development process is no longer needed to define, unless you still use the front and back end of the incomplete separation of the development model to use
Seven, code download address transmission Door