简体   繁体   English

如何在django-rest-framework的modelviewset中取消设置csrf?

[英]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.

相关问题 在django-rest-framework中将HyperLink添加到ModelViewSet - Add a HyperLink in django-rest-framework to a ModelViewSet django-rest-framework:使用相同的 ModelViewSet 渲染 HTML 和 JSON - django-rest-framework: Rendering both HTML and JSON with the same ModelViewSet django-rest-framework:在ModelViewSet中添加批量操作 - django-rest-framework: Adding bulk operation in a ModelViewSet 在 Django-REST-framework 中为 ModelViewSet 使用 defaultRouter() 时重定向错误 - Wrong redirects when using defaultRouter() for ModelViewSet in Django-REST-framework django-rest-framework如何决定`ModelViewSet`的默认`allowed_methods`应该是什么? - How does django-rest-framework decide what the default `allowed_methods` should be for a `ModelViewSet`? 创建时向django-rest-framework ModelViewSet添加其他字段的最佳方法 - best way to add additional fields to django-rest-framework ModelViewSet when create 如何在Django-rest-framework中更改编码 - How to change encoding in Django-rest-framework django-rest-framework,如何分页 - django-rest-framework, how to paginate 如何在 django-rest-framework 中使用 SearchFilter? - how to use SearchFilter in django-rest-framework? 如何覆盖 django rest 框架 ModelViewSet 中的更新操作? - How to override the update action in django rest framework ModelViewSet?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM