Django ------ csrf, ajax notes

### 1.csrf decorator `` `from django.views.decorators.csrf import csrf_exempt, csrf_protect, ensure_csrf_cookie csrf_exempt a view does not require csrf check csrf_protect a view needs to be csrf check ensure_csrf_cookie ensure that the cookie generated csrf `` `### 2.csrf 1.csrf middleware functions performed process_request: 1. acquired from the cookie to a value of` 2. csrftoken value csrftoken put into execution request.META 2. ` 1. query view function process_view whether csrf_exempt decorators, using checksum is not performed csrf 2. Analyzing request: 1. If a GET ',' HEAD ',' OPTIONS ',' TRACE 'not check csrf 2. other ways request (post, put) for csrf check: 1. get the value of the cookie csrftoken csrfmiddlewaretoken can obtain the value obtained - "request_csrf_token not obtain -" Get request header X-csrftoken value - "request_csrf_token request_csrf_token and comparing the value of the cookie csrftoken, successful reception request, rejects the request is unsuccessful comparison. ### 3.ajax 1. #### requesting the address bar enter the address mode 1. GET 2.form form GET / POST 3.a label technology is the use of GET #### 2.ajax js requesting and receiving responses. Features: 1. 2. partial refresh asynchronous data transmission 3. #### 3.jqery less ajax request issued `` `$ .ajax ({url: '/ calc /', type: 'post', data: {a: $ ( "[name = 'i1']") val (), b:.. $ ( "[name = 'i2']") val (),}, success: function (res) {$ ( "[name = 'i3']") val (res)}, error:. function (error) {console.log (error)}}) `` `#### 4. upload:` `` html . $ ( '# B1') click (function () {var formobj = new FormData (); formobj.append ( 'file', document.getElementById ( 'f1') files [0]);. // formobj.append ( 'file', $ ( '# f1') [0] .files [0]); formobj.append ( 'name', 'alex'); $ .ajax ({url: '/ upload /', type: 'post', data: formobj, processData: false, // contentType: false, success: function (res) {$ ( "[name = 'i3']") val (res).},})}) `` `#### 5.ajax by checking the csrf: Prerequisites: csrftoken ensure a cookie used in the page {% csrf_token%} plus decorator ensure_csrf_cookie from django.views.decorators.csrf import csrf_exempt, csrf_protect, ensure_csrf_cookie 1 adding to the data value csrfmiddlewaretoken of `` `html data: { 'csrfmiddlewaretoken': $ ( '[name =" csrfmiddlewaretoken "]') val (), a:. $ (" [name = 'i1'] ") .val (), b: $ ( "[name = 'i2']") val (),.}, `` `2. Add request header` `` html headers: { 'x-csrftoken':. $ ( '[Name = "csrfmiddlewaretoken"]') val (),}, `` `3. Use the same file mode 2

Guess you like

Origin www.cnblogs.com/anthony-wang0228/p/11096990.html