本文研究的主要是django在接受post請求時顯示403forbidden時的處理方法,具體代碼如下。
最近在做一個項目需要用到Django框架
在測試Django的時候發現一個問題,就是按照一般教程設置好URL的mapping之后,使用get請求總能得到正確的回應,但是在使用post請求時,卻根本無法得到請求,會顯示403forbidden:
1
2
3
4
|
Starting development server at http: / / 127.0 . 0.1 : 8000 / Quit the server with CTRL - BREAK. Forbidden (CSRF cookie not set .): / [ 23 / Mar / 2017 20 : 58 : 36 ] "POST / HTTP/1.1" 403 2857 |
根據提示(CSRF cookie not set)上網搜索了一下,發現只要在接收post請求的函數前加上csrf_exempt裝飾器就可以了:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# coding=utf-8 from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt import json # Create your views here. @csrf_exempt def index(request): if request.method = = 'POST' : body = json.loads(request.body) print body[ 'value' ] return HttpResponse(request.body) |
控制臺輸出為(傳入的body為{'value': 'test'}):
1
2
3
4
|
Starting development server at http: / / 127.0 . 0.1 : 8000 / Quit the server with CTRL - BREAK. test [ 23 / Mar / 2017 21 : 03 : 37 ] "POST / HTTP/1.1" 200 17 |
總結
以上就是本文關于django在接受post請求時顯示403forbidden實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/xavierqwb/article/details/65449189