【问题标题】:Django Load testing using locust giving Csrf token errorDjango负载测试使用蝗虫给出Csrf令牌错误
【发布时间】:2019-01-12 14:30:51
【问题描述】:

我正在为我的 django 应用程序编写负载测试脚本,但出现错误:

raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
KeyError: "name='csrftoken', domain=None, path=None"

这是我的脚本:

from locust import HttpLocust, TaskSet, task
import requests

class UserBehavior(TaskSet):
    def on_start(self):
        """ on_start is called when a Locust start before any task is scheduled """
        self.login()

    def login(self):
        response = self.client.get("/")
        csrftoken = response.cookies['csrftoken']
        self.client.post('/check_login/',{'username': '####', 'password': '########'},headers={'X-CSRFToken': csrftoken})


    @task(2)
    def index(self):
        self.client.get("/")

    @task(1)
    def profile(self):
        self.client.get("/home")

class WebsiteUser(HttpLocust):
    task_set = UserBehavior
    min_wait = 5000
    max_wait = 9000

在命令行中,我给出这个命令来启动 locust:locust --host=http://localhost:8080

有关如何纠正此错误的任何建议?

【问题讨论】:

  • 您找到解决方案了吗?我遇到了同样的问题

标签: django load-testing locust


【解决方案1】:

我遇到了同样的问题。

我有 Django 1.11 实例,并且 csrftoken 的名称是 other,在我的情况下是:

csrftoken = response.cookies['csrftoken_myproject']

并且我已经用Chromium browserdevtools 搜索了csrftoken 名称(例如)。

【讨论】:

    【解决方案2】:

    要使其工作有两个要求:

    1. csrftoken 应作为 csrfmiddlewaretoken 在表单数据中传递。
    2. 连同 X-CSRFToken 标头、Referer 标头 也是必需的。

    代码如下所示:

    self.client.post(
        '/check_login/',
        {
            'username': '####',
            'password': '########',
            'csrfmiddlewaretoken': csrftoken
        },
        headers={
            'X-CSRFToken': csrftoken,
            'Referer': self.parent.host + '/check_login/'
        })
    

    【讨论】:

      【解决方案3】:
       def on_start(self):
              self.login()
      
          def login(self):
              # login to the application
              self.client.auth = HTTPBasicAuth('username', 'password')
      

      这足以登录。无需在 python 中更新 csrftoken。 3.6.8

      【讨论】:

      • 这对我有用.. 谢谢。只需要从 requests.auth 导入 HTTPBasicAuth
      猜你喜欢
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      相关资源
      最近更新 更多