我想在Django中使用带有API视图的CSRF中间件。这是一个我想要使用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)
获取令牌
然后在客户端https://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"]}