3
我使用的服務器:Django的,Gunicorn,ngnix,PostgreSQL的CSRF驗證失敗。請求中止 - Django的,POST
Client: Chrome Advanced Rest Client
views.py
from django.views.decorators.csrf import csrf_exempt, **ensure_csrf_cookie** # Newly added
from django.http import HttpResponse
**@ensure_csrf_cookie** # newly added
def hello(request):
return HttpResponse("Hello world")
def hi(request):
return HttpResponse("Hi World")
def display_meta(request):
values = request.META.items()
values.sort()
html = []
for k, v in values:
html.append('<tr><td>%s</td><td>%s</td></tr>' % (k, v))
return HttpResponse('<table>%s</table>' % '\n'.join(html))
def addUser(request):
if request.method == 'POST':
# Convert JSON to python objects and
# store into the DB
print 'Raw Json "%s"' % request.body
#return HttpResponse("%s" %request.body)
return HttpResponse("Thank God")
url.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from requests import hello, hi, addUser, display_meta
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'testProject.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^hello/$', hello),
url(r'^hi/$', hi),
url(r'^admin/', include(admin.site.urls)),
url(r'^addPatient/$', addUser),
url(r'^displaymeta/$', display_meta),
)
manage.py
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dbTransactions',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
27,18 35%
從提前REST客戶端:
一)GET喜優良工程沒有錯誤 B)POST到ADDUSER賦予「 CSRF驗證失敗。請求中止「
我試了一下:
- @csrf_exempt的意見 - 在POST同樣的錯誤沒有變化
- 把X-CSRF令牌 - 在POST頭 - 無變化在POST 。同樣的錯誤
我將不勝感激這個幫助我已經閱讀:
- https://docs.djangoproject.com/en/dev/intro/tutorial01/
- http://www.djangobook.com/en/2.0/chapter12.html
你可以顯示你的前端表單嗎? – rnevius
用戶如何使用您的服務進行身份驗證?你可以導入csrf_exempt裝飾器,但是你沒有使用它 - 你可以有一個csrf_exempt GET視圖,把csrf標記放到響應中:'request.META [「CSRF_COOKIE_USED」] = True',然後在客戶端捕獲它與您的POST請求一起發送。 – henrikstroem
@rnevius我沒有任何前端形式。我正在考慮直接在iOS應用上使用此服務來發布數據。如果我的理解有缺陷,請糾正我。 – tesla