django middleware
When the request when the need to go through to get django middleware backend (urls, views, templates, models), response to go
Middleware also need to go through to get to a web service gateway interface
jango role of middleware
1. Web site global identity verification, access frequency restrictions, permissions check ... as long as it relates to the global checksum you can be done in middleware
2.django middleware is all done in the best web framework of
method
1.process_request () method of
law
when the request 1. The method will go through each of the intermediate process_request inside (from the top)
2. If the method returns directly inside HttpResponse object then returns directly down is not executed, based on this feature may be restricted access frequency, identity verification, rights verification
2.process_response () method of
law
1. the response parameter to be returned because the parameter refers to data is to be returned to the front end
2. response away when will in turn go through each broker inside process_response method (bottom-up)
3.process_view ()
1. In the match before routing the successful implementation of the view function triggers
4.process_exception ()
1. automatically executed when you view function error
5.process_template_response ()
1. When you return to the HttpResponse object must contain render attributes will trigger
DEF index (Request):
Print ( 'I am the index view function')
DEF render ():
return HttpResponse ( 'What the hell stuff')
obj = HttpResponse ( 'index')
obj.render = render
return obj
Summary: You just have parameter repsonse when you're writing middleware feels that she returned this reponse is to give the front end of the message
Custom Middleware
1. If you want your writing middleware to take effect it must first inherit MiddlewareMixin
2. When registering a custom middleware must ensure that the path not wrong
csrf CSRF
Internal principle
in that tricks the user to enter account input above the other, to the input name attribute is not set, hide achieve a written name and value attributes within the input box, the value is the value of the account beneficiary phishing sites
The random string has the following characteristics
1. Each visit is different in the same browser
2. different browsers will not be repeated
When 1.form form post request transmitted only do you need to write a word
{% csrf_token%}
2.ajax how to avoid sending a post request verification csrf
1. Now write {% csrf_token%} page, tag lookup using the acquired key information input
{ 'username': 'jason' , 'csrfmiddlewaretoken': $ ( '[ name = csrfmiddlewaretoken] '). val ()}
2. Direct Writing 'csrf_token {} {}'
{ 'username': 'Jason', 'csrfmiddlewaretoken': 'csrf_token {} {}'}
3. You can obtain the method writes a random key file js , after which only need to import the file, then a new file is stored js following code can be introduced
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); } } });
1. When you global site needs check csrf of how some do not need to check the processing
2. When not checking csrf when global site you need to check how should deal with several
from django.utils.decorators Import method_decorator from django.views.decorators.csrf Import csrf_exempt, csrf_protect # two decorators have some differences in the time to decorate the CBV If csrf_protect then there are three ways # The first method # @ method_decorator (csrf_protect, name = 'post ') # effective class the MyView (View): # third embodiment # @method_decorator (csrf_protect) DEF dispatch (Self, Request, * args, ** kwargs): RES = Super () .dispatch (Request, * args, ** kwargs) return RES DEFGET (Self, Request): return HttpResponse ( ' GET ' ) # The second method # @method_decorator (csrf_protect) # effective DEF POST (Self, Request): eturn HttpResponse ( ' POST ' ) if it is csrf_exempt only two ( means to dispatch only) Specific examples @method_decorator (csrf_exempt, name = ' dispatch ' ) # the second embodiment may not check class the MyView (View): # @method_decorator (csrf_exempt) # can not check the first embodiment DEF dispatch (Self, Request, * args, ** kwargs): RES= super().dispatch(request, *args, **kwargs) return res def get(self,request): return HttpResponse('get') def post(self,request): return HttpResponse('post')
Only csrf_exempt decorator is a special case, when other decorators to decorate the CBV can have three ways
auth module
if you want to use the auth module then you can use a full set
Auth module function
User queries from django.contrib Import auth USER_OBJ = auth.authenticate (username = username, password = password) # must be used because the database is password field and you get user input is plaintext ciphertext recording user state auth. the Login (Request, USER_OBJ) # user state record in the session to determine whether the user login Print (request.user.is_authenticated) # determine if a user is logged user you will return False users to access a user object after login Print (request.user) # If no auth.login then got an anonymous user if the user logs check from django.contrib.auth.decorators Import login_required @login_required (LOGIN_URL = ' / xxx /' ) # Local configuration DEF index (Request): Pass # global configuration settings file LOGIN_URL = ' / XXX / ' verify the password is correct request.user.check_password (old_password) Change password request.user.set_password (new_password) the request.user .save () # change your password when we must save or not save the entry into force logout auth.logout (Request) # request.session.flush () registered users # User.objects.create (username = username, password = password) # create a user name and then use the time do not create the # User.objects.create_user (username = username, password = password) # create a regular user User.objects.create_superuser (username = username, password = password, Email = ' [email protected] ' ) # Create a super user Email (required)
Custom auth_user table
from django.contrib.auth.models Import AbstractUser # . the Create your Models here Wallpaper # The first uses one relationship does not consider # inherited second way to use the class class Userinfo (AbstractUser): # Do not follow the original table the field can only repeat innovative Phone = models.BigIntegerField () Avatar = models.CharField (max_length = 32 ) # be sure to tell django in the configuration file # tell django orm no longer use the auth default table but use your custom table AUTH_USER_MODEL = ' app01.Userinfo ' # 'application name. class name'
1. Run the database migration command
all the auth module functions are all based on the table you created
instead of using auth_user