【问题标题】:Flask get csrf_token for Locust load testingFlask 获取 csrf_token 用于 Locust 负载测试
【发布时间】:2017-08-09 11:20:32
【问题描述】:

我想用我的远程服务器实现对 locust 的负载测试,但我不想禁用 csrf 功能,我怎样才能获得 csrf_token 或绕过它

class UserBehavior(TaskSet):
    @task(1)
    def login(self):
        self.client.get("/securities/login") 
        token = "how to get it" 
        self.client.post("/securities/login",{"username":"test", 
                                              "password":"123",
                                              "csrf_token":token})

【问题讨论】:

    标签: python flask locust


    【解决方案1】:
      result = self.client.get("/securities/login") 
      token = result.cookies['_csrf_token'] # i think this is the name anyway you could always print result.cookies to find out 
    

    至少我认为...我知道这在 djanjo 中有效

    使用烧瓶可能需要更多的工作......请参阅此要点https://gist.github.com/singingwolfboy/2fca1de64950d5dfed72

    【讨论】:

    • cookies['_csrf_token'] 和 cookies['csrf_token'] 不起作用
    • 您尝试打印 result.cookies 吗?
    • 缓存对象看起来很难看到]> 跨度>
    【解决方案2】:

    如果你使用 Flask_WTF,你可以像这样得到csrf token

    from flask import Flask
    from flask_wtf import FlaskForm
    app = Flask(__name__)
    app.secret_key = 'random string'
    
    class HelloForm(FlaskForm):
        # ...
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = HelloForm()
        token = form.csrf_token.data
    

    相反,您也可以自己生成令牌:

    from hashlib import md5
    
    def generate_csrf_token():
        token = md5(app.secret_key).hexdigest()
        return token
    

    【讨论】:

      【解决方案3】:

      我找到了找到令牌的方法

      import re
      class UserBehavior(TaskSet):
          @task(1)
          def login(self):
              result = self.client.get("/securities/login") 
              token = re.search(r'[0-9]{10}##[a-z0-9]{40}',result.text).group(0)
              print token
      

      除了 re(RegularExpression) 之外的另一种方法是使用 PyQuery 从 html 表单元素中获取令牌键。

      【讨论】:

        猜你喜欢
        • 2017-04-14
        • 2021-03-18
        • 2020-01-02
        • 2020-05-17
        • 2019-01-22
        • 2019-12-26
        • 2019-09-18
        • 2021-07-29
        • 1970-01-01
        相关资源
        最近更新 更多