【问题标题】:how to keep session and CSRF token in locus test如何在轨迹测试中保留会话和 CSRF 令牌
【发布时间】:2015-01-04 10:03:58
【问题描述】:

我不想用 locust.io 测试我的 django 网络应用程序。在 ha 形式中,我遇到的问题是它使用 CSRF 令牌进行保护。我执行以下操作:

class WebsiteTasks(TaskSet):
    def on_start(self):
        print("On start")

    @task
    def post_answer(self):
        self.client.get("/polls/2/vote")
        self.client.post("/polls/2/vote/", {"choice": "8"})

为什么我会收到 403 错误?该帖子是fobidden的,蝗虫文档说客户端对象使会话保持活动状态..

【问题讨论】:

    标签: debugging csrf locust


    【解决方案1】:

    将您的代码更改为:

    @task
    def post_answer(self):
        response = self.client.get("/polls/2/vote")
        csrftoken = response.cookies['csrftoken']
    
        self.client.post("/polls/2/vote/", 
                         {"choice": "8"}, 
                         headers={"X-CSRFToken": csrftoken})
    

    【讨论】:

    • 我认为这将在 flask-wtf 上失败。我应该解析“session=....”以获取烧瓶中的 csrftoken 吗?
    • 你还需要在cookies中发送token
    【解决方案2】:

    我在针对 Django 1.8.5 运行 Locust 测试时遇到了这个问题,它需要将 csrf 令牌添加到 cookie、标头和表单 POST 数据以及如下所示,以免遇到 403。喜欢:

    @task
    def post_answer(self):
        response = self.client.get("/polls/2/vote")
        csrftoken = response.cookies['csrftoken']
    
        self.client.post("/polls/2/vote/", {"choice": "8",
                         "csrfmiddlewaretoken": csrftoken}, 
                         headers={"X-CSRFToken": csrftoken},
                         cookies={"csrftoken": csrftoken})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      • 2020-02-10
      • 2021-02-24
      • 2014-01-23
      • 2014-08-20
      • 2023-01-24
      • 2012-03-20
      相关资源
      最近更新 更多