将 django CSRF 中间件与返回 JsonResponse 的视图一起使用
Using django CSRF middleware with views returning JsonResponse
我想在 Django 中将 CSRF 中间件与 API 视图一起使用。这是我想使用 CSRF 的演示视图,我很困惑如何在此处集成 CSRF。
def login(request):
try:
if len(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))==1:
print(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))
return JsonResponse({'exit':'0','msg':'Success'})
return JsonResponse({'exit':'2','msg':'User Invalid'})
except Exception as e:
return JsonResponse({'exit':'10','msg':'Unknown Error Occured'})
如有任何帮助或建议,我们将不胜感激。谢谢
您可以通过django.middleware.csrf.get_token(request)
获得令牌
然后在请求的头部设置client-sidehttps://docs.djangoproject.com/en/2.0/ref/csrf/#setting-the-token-on-the-ajax-request
django.middleware.csrf.get_token(request)
好的,这将满足您的需求
要在响应中设置 cookie,请使用 @ensure_csrf_cookie
装饰器:
from django.views.decorators.csrf import ensure_csrf_cookie
@require_http_methods(["GET"])
@ensure_csrf_cookie
def list_things(request):
return JsonResponse({
"things": ["foo", "bar"],
})
$ curl -i http://localhost:8000/api/v1/things
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Cookie
Set-Cookie: csrftoken=nm4SdMB0pobkQ1ab7wZTFdwMlX8wr0vfT4iAg6Nqpcatl7ITRi9VOHrKf0Krbp2i; expires=Thu, 05 Mar 2020 15:25:53 GMT; Max-Age=31449600; Path=/; SameSite=Lax
{"things": ["foo", "bar"]}
我想在 Django 中将 CSRF 中间件与 API 视图一起使用。这是我想使用 CSRF 的演示视图,我很困惑如何在此处集成 CSRF。
def login(request):
try:
if len(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))==1:
print(DemoTable.objects.filter(phone=int(request.POST['user'])).filter(password=sha1Engine(request.POST['password'])))
return JsonResponse({'exit':'0','msg':'Success'})
return JsonResponse({'exit':'2','msg':'User Invalid'})
except Exception as e:
return JsonResponse({'exit':'10','msg':'Unknown Error Occured'})
如有任何帮助或建议,我们将不胜感激。谢谢
您可以通过django.middleware.csrf.get_token(request)
然后在请求的头部设置client-sidehttps://docs.djangoproject.com/en/2.0/ref/csrf/#setting-the-token-on-the-ajax-request
django.middleware.csrf.get_token(request)
好的,这将满足您的需求
要在响应中设置 cookie,请使用 @ensure_csrf_cookie
装饰器:
from django.views.decorators.csrf import ensure_csrf_cookie
@require_http_methods(["GET"])
@ensure_csrf_cookie
def list_things(request):
return JsonResponse({
"things": ["foo", "bar"],
})
$ curl -i http://localhost:8000/api/v1/things
HTTP/1.1 200 OK
Content-Type: application/json
Vary: Cookie
Set-Cookie: csrftoken=nm4SdMB0pobkQ1ab7wZTFdwMlX8wr0vfT4iAg6Nqpcatl7ITRi9VOHrKf0Krbp2i; expires=Thu, 05 Mar 2020 15:25:53 GMT; Max-Age=31449600; Path=/; SameSite=Lax
{"things": ["foo", "bar"]}