Django middleware
django life cycle chart
Middleware:
The concept : Django is similar to django middleware security
Request time middleware needs to go through to get django backend (urls, views)
In response take the time to go through middleware to reach the web service gateway interface
django default seven middleware
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
Q: django middleware can be used to do ***?
1. Web site global identity verification, access frequency limit, the authority verification .....
2.django middleware is a web framework do best
There are five methods Django middleware user can customize
process_response process_request process_view process_exception process_templates
How do you customize?
① first you need the same level in the app catalog to create your own middleware to create your py files in it
② import module from django.utils.deprecation import MiddlewareMixin
③ define your own class needs to inherit the top five ways to rewrite Middleware
④ settings in the configuration file MIDDLEWARE added points of the character string, for example: '.py file folder class name'
process_request(request) 方法
Law: 1. request time to go through the inside of each intermediate process_request method ( from top to bottom )
2. If the direct method which returns a HttpResponse objects that will not back down to perform the same level of execution process_response method to go back
3. The method must be incoming request parameter that is based on the access frequency characteristics can be done to verify the identity, rights verification
process_response(request, response) 方法
Rules: 1. The parameters must reponse return because this parameter is returned by the backend to the frontend data
2. The response time to go through each in turn middleware inside process_response method (bottom-up)
Learn how to:
process_view(request, view_func,view_args, view_kwargs)
Before performing the trigger function triggers after routing a successful match
view_func url is a view corresponding matching function parameters are view_args and view_kwargs
process_exception( request,exception)
When you view function being given back to the automatic trigger
process_template_response(request, response)
When you back HttpResponse object must contain render attributes will trigger
Summary : writing middleware time as long as there is response parameter put it returns the data he needs is a front end
csrf CSRF
Introduction: Fishing Website: eight children with a site exactly the same interface to cheat users input information to modify the data produced by the eight sites submitted positive children
Internal principle: let the user input to play tricks do not give the input and set the name attribute to hide a written name and attribute value input box in the input box inside on the other side of the transfer value is the beneficiary of the account form of phishing sites form data submitted instead of eight children
Prevent phishing sites ideas
website will return to the form page form to the user secretly stuffed a random string
request comes will first than random strings are the same if not directly reject (403)
The random string has the following characteristics
1. Each visit is different in the same browser
2. different browsers will not be repeated
-------------------------------------------------------------------------------------------------------------------------------------------
1. When a form to send post request form you need to do is just write a word {{% csrf_token%}}
So that we can have a right middleware opened his comments is to verify that you do not have a csrfmiddlewaretoken something not directly give you 403
2. When such a request ajsx transmission and avoid post verification csrf
1. First write {% csrf_token%} on the page, using the tag name attribute finder Find the acquired key information input
2. Direct Writing '{{csrf_token}}'
3. The method of obtaining random key-value pairs wrote a js file after file you can just import
Js files and create files in the static py file after the following line of code written in the lead
function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function (xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } });
After how to pass on how to pass on the line
1. When the global need to check your site csrf when there are a few do not need to check how this process?
2. When the global website you do not check csrf need when there are several check what should we do?
from django.views.decorators.csrf import csrf_exempt,csrf_protect
csrf_exempt not check
csrf_protect only check
cbv decoration
from django.utils.decorators import method_decorator
Both decorator is quite different when a decorative CBV If so, there are three ways csrf_protect # a first embodiment # @method_decorator (csrf_protect, name = 'POST') # effective class the MyView (View): # of three ways # @method_decorator (csrf_protect) DEF dispatch (Self, Request, * args, ** kwargs): RES = Super () dispatch (Request, * args, **. kwargs) return RES DEF GET (Self, Request) : return HttpResponse ( ' GET ' ) # second way # @method_decorator(csrf_protect) # 有效的 def post(self,request): return HttpResponse('post')
If only two csrf_exempt (only means to dispatch) Specific examples @method_decorator (csrf_exempt, name = 'dispatch') # the second embodiment may not check class the MyView (View): # @method_decorator (csrf_exempt) of the first # species may not verify manner DEF dispatch (Self, Request, * args, ** kwargs): RES = Super () dispatch (Request, * args, **. kwargs) return RES DEF GET (Self, Request): return the HttpResponse ( ' GET ' ) DEF POST (Self, Request): return the HttpResponse (' POST ' )
decorator only csrf_exempt is a special case, when other decorators to decorate the CBV can have three ways
def login_auth(func): @wraps(func) def inner(request,*args,**kwargs): # 从request中获取cookie # print(request.path) # print(request.get_full_path()) target_url = request.get_full_path() if request.COOKIES.get('name'): res = func(request,*args,**kwargs) return res else: return redirect('/lg/?next=%s'%target_url) return inner
auth module
Introduction: (if you want to use the auth module then use the full set) auth module is associated with the user function module
① After executing the database migration command will have a lot of tables which form auth_uesr is a user-related .
② add data createsuperuser create a super user can have the super-user privileges to log in django admin background
Set mailbox user name and password auth_user table will take you to record data and to log in admin
auth module function
Import module
from django.contrib import auth
Direct view function using the sub-ah
Query User
user_obj = auth.authenticate(username='xxx', password='xxx')
Record user status
auth.login(request,user_obj)