如何在测试Django中禁用CSRF? [英] how to disable csrf in testing django?

查看:123
本文介绍了如何在测试Django中禁用CSRF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用csrf令牌测试视图时遇到问题。

I have a problem testing views with csrf tokens.

此代码

class ViewTests(TestCase):
    def test_bets_view(self):
        login_page = self.client.get('/users/login/')
        print(login_page.content)

返回带有CSRF隐藏输入的HTML。

returns HTML with CSRF hidden input.

这是我需要与以前的HTML进行比较的东西,

And this thing, which I need to compare to the former HTML,

expected_html = render_to_response('login.html',
                                   dictionary={'form': LoginForm()})

没有隐藏的CSRF输入。

doesn't have hidden CSRF input. So the assertion fails.

我如何在测试客户端中禁用CSRF渲染?

Ho do I disable CSRF rendering in test client?

推荐答案

永远不要比较完整的HTML内容。只需检查功能即可。万一您需要不惜一切代价禁用 csrf ,以下逻辑应该对我有所帮助。

You should never compare the complete HTML content. Just check the functionalities. In case you need disabling the csrf at any cost, following logic should help I guess.

在您的 views.py 文件,添加以下软件包

In your views.py file, add the following package

从django.views.decorators.csrf导入csrf_exempt

然后在要执行检查的函数定义之前,添加以下代码段:

Then just before the function definintion, in which you are performing your checks, add this snippet:

@csrf_exempt

这将禁用csrf的默认验证。即使您的传入请求具有隐藏的csrf令牌,您的服务器功能也会完全忽略它。这应该是禁用csrf的技巧。

This will disable the default verification of csrf. Even if your incoming request has a hidden csrf token, your server function will completely ignore it. This should do the trick of disabling the csrf.

这篇关于如何在测试Django中禁用CSRF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆