【问题标题】:Django testing - spoofing an Ajax POST request method with Client() to pass request.is_ajax() validationDjango 测试 - 使用 Client() 欺骗 Ajax POST 请求方法以通过 request.is_ajax() 验证
【发布时间】:2018-08-22 23:40:19
【问题描述】:

不确定这是否可行,但我在views.py 中对 Ajax POST 请求进行了以下验证检查:

if request.is_ajax() and request.method == 'POST':
    # Do some amazing stuff here...
    context['is_ajax'] = True

现在,在 shell 中运行一些测试:

from django.test import Client
>>> c = Client()
>>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
>>> response.context['is_ajax']
>>> undefined

所以我的问题是,测试客户端是否有办法欺骗 Ajax 请求...通过对请求 POST 对象的is_ajax() 验证检查,这是通过向标头添加内容来完成的吗?

我认为标头应该是 HTTP_X_REQUESTED_WITH='XMLHttpRequest' - 如何将其传递给 c.post() 方法?

【问题讨论】:

    标签: django django-tests


    【解决方案1】:

    所以在你的情况下,它会是这样的

    response = c.post('/login/', {'username': 'john', 'password': 'smith'},
                              HTTP_X_REQUESTED_WITH='XMLHttpRequest')
    

    希望能指引你正确的方向。

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 1970-01-01
      • 2019-12-01
      • 2014-12-16
      • 2013-03-15
      • 2015-05-30
      • 2021-11-01
      • 2012-06-22
      • 2021-01-05
      相关资源
      最近更新 更多