Fifty-two, django middleware, csrf cross-site request forgery, auth table module

django middleware
    something similar to django django middleware security, when the request needs to go through to get django middleware backend (urls, views, templates, models ), 
    response take the time to go through middleware to reach the web service gateway interface
django middleware There are five ways users can customize the 
django middleware can be used to do what?
1. Web site global identity verification, access frequency limit, check the permissions. . As long as the check involves the global can be done in the middleware
2.django all web middleware framework, do the best

method to master are:
Method 1.process_request ()
Law
1. request time, after each intermediate methods will process_request inside
time 2. the request will be executed process_request down sequentially from the method, if not directly skip to the next
3. when process_request () method, return HttpResponse ( "" ) object, the value is returned directly to the browser, middleware and back view layer not go
based on the frequency characteristics can be done to limit access, identity verification, permission check

method 2.process_response ()
rule
1. in response to go time. After execution until view function will be executed sequentially process_response up by the method, will skip if not, go to the next
2. The response must return, because the response parameter to refer to the data is returned to the front end of

understanding:
3.process_view ()
# In the route matches, fires before view function is executed
4.process_exception ()
# long as the view function Once the error, immediately triggers process_exception method
5.process_template_response ()
# When you return to the HttpResponse object must contain attributes will trigger render

summary : as long as the response parameter, it must return, to the front-end response is the

custom of our own middleware:
1. If you want to customize the middleware, it must inherit MiddlewareMixin
2. definition of middleware, go to settings inside Add middleware manual

from django.utils.deprecation Import MiddlewareMixin
 from django.shortcuts Import HttpResponse 


class MyMdd (MiddlewareMixin):
     DEF process_request (Self, Request):
         Print ( " I was the first middleware process_request method " )
         # return HttpResponse ( "funny than" ) 

    DEF process_response (Self, Request, the Response):
         Print ( " I was the first middleware process_response method " )
         # Print (the Response) 
        return the Response 

    DEFprocess_view (Self, Request, view_func, view_args, view_kwargs):
         Print (view_func)
         Print (view_args)
         Print (view_kwargs)
         Print ( " I was the first middleware process_view method " ) 

    DEF process_exception (Self, Request, Exception):
         Print ( " I was the first process_exception " ) 

    DEF process_template_response (Self, Request, the Response):
         Print ( " I was the first middleware process_template_response method " )
         return the Response 

classMyMdd1 (MiddlewareMixin):
     DEF process_request (Self, Request):
         Print ( " I was the second middleware process_request method " ) 

    DEF process_response (Self, Request, the Response):
         Print ( " I was the second middleware process_response method " )
         return the Response 

    DEF process_view (Self, Request, view_func, view_args, view_kwargs):
         Print (view_func)
         Print (view_args)
         Print (view_kwargs)
         Print ( " I was the second middleware process_view method " ) 

    DEFprocess_exception (Self, Request, Exception):
         Print ( " I was the second process_exception " ) 

    DEF process_template_response (Self, Request, the Response):
         Print ( " I was the first middleware process_template_response method " )
         return the Response
Custom middleware code

 

csrf CSRF

phishing sites: simply put, is the website page to the user exactly the same, allowing users to enter transfer information, by hiding the label, the equipment to each other's information, make changes, for their own purposes

to prevent the idea of phishing websites:
website will return the user's form form page secretly stuffed a random string
request comes will first than random strings are the same, if not directly reject

the random string has the following characteristics:
1. each time the same browser access is not the same
2. different browsers will not repeat

1.form form is sent when you need to post a request form to write in the form:
{%}% csrf_token
2.ajax send post requests on how to avoid csrf check
1. first write {% csrf_token%} on the page, using the tag lookup to obtain the input key information
Data: { 'username': 'Jason', 'csrfmiddlewaretoken': $ ( '[name = csrfmiddlewaretoken]') Val ().},
2 direct writing csrf_token} {} {
Data: { 'username': 'Jason', 'csrfmiddlewaretoken': 'csrf_token {} {}'},
3. you can obtain the method writes a random key js file, then introduced to
{% load static%}
{#<script src="{% static 'setjs.js' %}"></script>#}
<script>
$ ( '# B1') the Click (function () {. 
            $ .ajax ({ 
                URL: '', 
                type: 'POST', 
                // first way 
                data: { 'username': ' jason', 'csrfmiddlewaretoken' : $ ( '[name = csrfmiddlewaretoken]') Val ()},. 
                // second approach 
                Data: { 'username': 'Jason', 'csrfmiddlewaretoken': 'csrf_token {} {}'}, 
                // first in three ways: directly introduced js file 
                Data: { 'username': 'Jason'}, 
                Success: function (Data) { 
                    Alert (Data) 
                } 
            }) 
        </ Script >

1. When you which ones the global need to check back 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
# school experience CSRF
from django.views.decorators.csrf Import csrf_exempt, csrf_protect #
from django.utils.decorators Import method_decorator
both decorated in CBV decorated differently

csrf_exempt canceled check
can only display plus decorator
@method_decorator (csrf_exempt) # The first test may not
DEF dispatch (Self, Request, * args, ** kwargs):
return Super () dispatch (Request, * args, ** kwargs).

csrf_protect check, three ways

# The first verify mode: 
        # @method_decorator (csrf_protect, name = "post") 
        class the MyView (View):
             # third check ways: 
            # @method_decorator (csrf_protect) # in this way get and post are coupled the 
            DEF dispatch (Self, Request, * args, ** kwargs):
                 return . Super () dispatch (Request, * args, ** kwargs) 

            DEF GET (Self, Request):
                 return HttpResponse ( " GET " ) 

            # second ways: 
            # @method_decorator (csrf_protect) 
            DEF POST (Self, Request):
                 return HttpResponse ( "post")
auth module table
after performing database migration can generate a lot of them auth_user table is a table associated with the user
add data
to perform createsuperuser create a superuser super user can log in django admin backend
method:
1. # auth query table
user_obj = auth. the authenticate (username = username, password = password)
# where a lookup table, returns an object, which is the password stored ciphertext


2.auth.login (Request, USER_OBJ) # user state table recorded in the session, the client session supra
# execution as long as you can get this word to the current user objects in the rear end by request.user anywhere "" "
# Print (request.user.username)
# Print (request.user.password)

3. determine whether the user landing, landing is True
# request.user.is_authenticated)


4. Change password ways:
is_right = request.user.check_password (old_password) # automatically encrypted, password verification database is correct
if is_right: # check correct is True
Print (is_right)
request.user.set_password (new_password) # set a new password
request.user.save () # save the modified password information



5. Log off
# cancellation
@login_required
DEF Zimbabwe Logout (Request):
auth .logout (request) session ends before and after # are deleted together equivalent to the flush
return the HttpResponse ( "quit")

the auth login module decorator
from django.contrib.auth.decorators import login_required
may be disposed inside settings:
LOGIN_URL = " / land / ", after landing are transferred to this page


with a custom auth table, you can add fields, while using auth module syntax
from django.db Import Models
from django.contrib.auth.models Import AbstractUser
The second way to use class inheritance can add fields with auth table
class Userinfo (AbstractUser):
# Do not repeat the only innovation in the field with the original table
Phone = models.BigIntegerField ()
Avatar = models.FileField (upload_to = " / avatar ")

also you need to tell django not use the default table configuration file
tells the table before django no longer used, use a self-defined list of
AUTH_USER_MODEL =" app01.Userinfo "# application name. class name

Guess you like

Origin www.cnblogs.com/wukai66/p/11604461.html