在django、csrf_token上测试post请求

时间:2021-12-26 06:40:01

I am trying test some of the post methods in my Django app, but due to the csrf_token, I can not test it without a browser. So I used @csrf_exempt decorator However I forget to remove those decorators in production. Is there a better way like this?

我正在测试Django应用程序中的一些post方法,但是由于csrf_token,我无法在没有浏览器的情况下测试它。因此我使用了@ csrf_豁免权decorator,但是我忘记了在生产中删除这些decorator。有更好的办法吗?

@csrf_exempt(in_debug_only=True)

@csrf_exempt(in_debug_only = True)

So like this decorator is active only when the application is in debug mode. Or is there a better way to test post requests?

因此,就像这样,decorator只有在应用程序处于调试模式时才会激活。或者有更好的方法来测试post请求吗?

Like selenium might have some methods to do that?

像selenium可能会有一些方法来实现这一点?

Note: I m currently using Django 1.7.2 and Python 3.4.1

注意:我目前正在使用Django 1.7.2和Python 3.4.1

1 个解决方案

#1


1  

Inspired by this answer:

灵感来自这个答案:

You can add a new file to your app, let's call it disable_csrf.py:

你可以给你的应用添加一个新的文件,我们叫它disable_csrf.py:

class DisableCSRF(object):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)

Then you can edit your settings.py to add this:

然后你可以编辑你的设置。py添加:

if DEBUG:
    MIDDLEWARE_CLASSES += myapp.disable.DisableCSRF

Let me know if it worked.

如果有用的话,请告诉我。

#1


1  

Inspired by this answer:

灵感来自这个答案:

You can add a new file to your app, let's call it disable_csrf.py:

你可以给你的应用添加一个新的文件,我们叫它disable_csrf.py:

class DisableCSRF(object):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)

Then you can edit your settings.py to add this:

然后你可以编辑你的设置。py添加:

if DEBUG:
    MIDDLEWARE_CLASSES += myapp.disable.DisableCSRF

Let me know if it worked.

如果有用的话,请告诉我。