Python path-(Django (CSRF, middleware, cache, signal, model operation, form operation))

Source: Internet
Author: User
Tags csrf attack

CSRF Middleware Cache Signal Model Operation Form Action

Csrf:  

How long has it been with Django that I've been dealing with the CSRF concept for a long time?

    • You can see django.middleware.csrf.CsrfViewMiddleware this middleware every time you initialize a project
    • Every time you write a form in a template, you know that you want to add a {% Csrf_token%} tag
    • Each time you send an AJAX POST request, you need to add a X_csrftoken header
What is CSRF

CSRF, Cross site request forgery, forged requests across sites. For example, a malicious website has a link to your site, if

A user is already logged on to your website, so when the user clicks on that link on the malicious site, a request is sent to your site,

Your website will think that this request is sent by the user itself, in fact, this request is the malicious website forged.

The CSRF protection mechanism provided by Django

When Django responds to a request from a client for the first time, a token is randomly generated on the server side, placing the token in a cookie. Then each POST request will be brought with this token,

This will prevent the CSRF from being attacked.

    1. In the cookie for the returned HTTP response, Django adds a csrftoken field for you, with a value of automatically generated tokens
    2. In all the POST forms, you must include a Csrfmiddlewaretoken field (just add a tag to the template, and Django will automatically generate it for you, see below)
    3. Before processing the POST request, Django verifies that the value of the Csrftoken field in the cookie for the request is the same as the value of the Csrfmiddlewaretoken field in the submitted form. If the same, this is a legitimate request, otherwise, the request may be from someone else's csrf attack, return 403 Forbidden.
    4. In all Ajax POST requests, add a X-csrftoken header whose value is the value of the Csrftoken in the cookie

How to use CSRF protection in Django
    • First, the most basic principle is that get requests do not have side effects. This means that any code that handles a GET request must be "read-only" to access the resource.
    • To enable Django.middleware.csrf.CsrfViewMiddleware this middleware
    • Again, in all the POST form elements, you need to add a {% Csrf_token%} tag
    • When rendering the module, use RequestContext. RequestContext will process Csrf_token this tag to automatically add an input named Csrfmiddlewaretoken to the form.

Middleware:

Operation:

First, create a folder within the project, and then create a. py file of any name in this folder, the basic content of this file is as follows:

  

 fromDjango.utils.deprecationImportmiddlewaremixinclassRow1 (middlewaremixin):defprocess_request (self,request):Print('Request--"Agent 1')    defProcess_response (self,request,response):Print('back--"Agent 6')        returnResponseclassRow2 (middlewaremixin):defprocess_request (self,request):Print('Request--"Agent 2')    defProcess_response (self,request,response):Print('back--"Agent 5')        returnResponseclassRow3 (middlewaremixin):defprocess_request (self,request):Print('Request--"Agent 3')    defProcess_response (self,request,response):Print('back--"Agent 4')        returnResponse

Registered:

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',    'Middle.m1.Row1',    'Middle.m1.Row2',    'Middle.m1.Row3',]

  

Middleware Order

In general, we send a request from the browser requesting that a response be sent to the HttpResponse, which is passed to Django as follows, and the process request and process response are executed in the opposite order, as shown in:

  

Cache:

Since Django is a dynamic Web site, every request will go to the corresponding operation of the data, when the program access is large, time is bound to be more obvious, the simplest solution is to use: cache, the cache will be a certain views of the return value of the memory or Redis, in 5 minutes when someone comes to visit, Instead of performing the operation in view, it is taken directly from memory or previously cached content in Redis and returned.

  

1. Prepare a dynamic website urls.py
 from Import  = [    url (r'^admin/', admin.site.urls),    URL (r')  ^cache/$', Views.cache),]

cmdb/views.py
Import  Time def Cache (Request):     = Str (time.time ())    return HttpResponse (current)

2. Create a cache directory

          

3. configuration file settings.py
CACHES = {    'default': {        'Backend':'Django.core.cache.backends.filebased.FileBasedCache',#file Mode        ' Location': Os.path.join (Base_dir,'Cache'),        'TIMEOUT': 600,        'OPTIONS': {            'max_entries': 1000        }    }}

4. Application
 from Import cache_page @cache_page (*)    # cache for 15 minutes def Cache (Request):     = Str (time.time ())    return HttpResponse (current)

5. Verification

The timestamp is refreshed only once and is cached, and then the refresh is not changed, and the cache string is read. At the same time, 2 static cache files are generated:

          

Signal:

Django built-in signal

  

Model Signals Pre_init#The Django modal automatically fires before executing its construction method.Post_init#when Django's modal executes its construction method, it automatically triggersPre_save#The Django Modal object is automatically triggered before it is savedPost_save#when the Django modal object is saved, it is automatically triggeredPre_delete#automatically triggers a Django modal object before it is deletedPost_delete#automatically triggers when a Django modal object is deletedM2m_changed#automatically triggers before and after the third table (Add,remove,clear) in the Django modal using the auto-Work fieldClass_prepared#when the program starts, detects registered apps in the modal class, for each class, automatically triggersManagement Signals Pre_migrate#automatic triggering before executing the migrate commandPost_migrate#automatically triggers after executing the migrate commandrequest/Response Signals request_started#Auto-Trigger before request arrivesRequest_finished#automatically triggered when the request is completeGot_request_exception#automatic triggering after an exception is requestedTest Signals setting_changed#automatically triggers when a configuration file is modified using test testsTemplate_rendered#automatically triggers when a render template is tested with testDatabase Wrappers connection_created#automatically triggers when a database connection is created

For a Django built-in signal, you only need to register the specified signal and automatically trigger the registration function when the program performs the appropriate action:

 fromDjango.core.signalsImportrequest_finished fromDjango.core.signalsImportrequest_started fromDjango.core.signalsImportgot_request_exception fromDjango.db.models.signalsImportclass_prepared fromDjango.db.models.signalsImportPre_init, Post_init fromDjango.db.models.signalsImportPre_save, Post_save fromDjango.db.models.signalsImportPre_delete, Post_delete fromDjango.db.models.signalsImportm2m_changed fromDjango.db.models.signalsImportpre_migrate, Post_migrate fromDjango.test.signalsImportsetting_changed fromDjango.test.signalsImporttemplate_rendered fromDjango.db.backends.signalsImportconnection_createddefCallback (sender, * *Kwargs):Print("Xxoo_callback")        Print(Sender,kwargs) Xxoo.connect (callback)#Xxoo refers to the contents of the above import

 from Import request_finished  from Import receiver@receiver (request_finished) def my_callback (sender, * *Kwargs)    :print("Request finished! ")

Custom Signal

1. Define the Signal

Import= django.dispatch.Signal (providing_args=["toppings"" size "])

2. Registration signal

def Callback (sender, * *Kwargs)    :print("callback"  )    print(Sender,kwargs) Pizza_done.connect (callback)

3. Trigger Signal

 from Import pizza_done pizza_done.send (Sender='seven', toppings=123, size=456)

Model Operation:

Form operation:

Python path-(Django (CSRF, middleware, cache, signal, model operation, form operation))

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.