[英]How to unset csrf in modelviewset of django-rest-framework?
How to unset csrf in modelviewset of django-rest-framework? 如何在django-rest-framework的modelviewset中取消设置csrf?
I'll use viewsets.ModelViewSet( http://django-rest-framework.org/api-guide/viewsets.html#modelviewset ) of django-rest-framework. 我将使用django-rest-framework的viewsets.ModelViewSet( http://django-rest-framework.org/api-guide/viewsets.html#modelviewset )。
And my app is api server. 我的应用程序是api服务器。 So I don't need to use csrf. 所以我不需要使用csrf。
But I don't know how to unset csrf. 但我不知道如何取消csrf。
Please give me a example! 请举个例子!
You need to wrap dispatch method of ModelViewSet with csrf_exempt : 您需要使用csrf_exempt包装ModelViewSet的 dispatch方法:
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
class MyModelViewSet(viewsets.ModelViewSet):
@method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(MyModelViewSet, self).dispatch(*args, **kwargs)
or you can achieve the same effect by wrapping the view in urls.py : 或者你可以通过在urls.py中包装视图来实现相同的效果:
url(r'^snippets/$', csrf_exempt(snippet_list), name='snippet-list'),
url(r'^snippets/(?P<pk>[0-9]+)/$', csrf_exempt(snippet_detail), name='snippet-detail'),
CSRF is only enforced if you're using SessionAuthentication. 只有在使用SessionAuthentication时才会强制执行CSRF。 If you're using one of the other form of authentication (eg TokenAuthentication) then it won't be required. 如果您正在使用其他形式的身份验证(例如TokenAuthentication),则不需要它。
还要确保您的urlpatterns中不包含api-auth。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.