python - Locustio(Python)登录

标签 python http python-requests load locust

我想在网站上做一些负载测试。 首先,这是我的代码:

from locust import HttpLocust, TaskSet, task

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):
    post_data = {'username':'my_login', 'password':'my_pass', 'Login':'Login'}
    with self.client.post('/sign_in', post_data, catch_response=True) as response:
        if 'cookie' not in response.cookies:
            response.failure('login failed')
@task(2)
def index(self):
    self.client.get("/admin")

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

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

我正在运行蝗虫:locust --host= https://my_host .

我总是收到 405 err 错误报告:

11 POST/sign_in: "CatchResponseError('登录失败',)"

有人可以向我解释如何确保我已登录以及如何使用 Locust 执行此操作吗? 我有点困惑,因为我也尝试过让事情与 token 等一起工作,但仍然是一样的。

最佳答案

您可能需要尝试一些“愚蠢”的事情,具体取决于您的 API 的工作方式,如下所示:

  1. 尝试在端点后附加一个尾部斜杠 (/),例如'/sign_in/' 而不是 '/sign_in'
  2. 出于某种原因,当我在我的主机变量中使用 http 时出现错误,但当我使用 https 时它工作正常。您可能也想尝试一下。
  3. 确保您没有忘记端点中的版本(如果有的话)。例如,'https://my_host/v1/sign_in/'

至于使用 token 登录,下面的代码对我来说工作正常:

from locust import HttpLocust, TaskSet, task
import json


class UserBehavior(TaskSet):

    def __init__(self, parent):
       super(UserBehavior, self).__init__(parent)

       self.token = ""
       self.headers = {}

   def on_start(self):
      self.token = self.login()

      self.headers = {'Authorization': 'Token ' + self.token}

  def login(self):
      response = self.client.post("/sign_in/", data={'username':'my_login', 'password':'my_pass', 'Login':'Login'})

    return json.loads(response._content)['key']

 @task(2)
 def index(self):
     self.client.get("/admin/", headers=self.headers)

 @task(1)
 def profile(self):
     self.client.get("/profile/", headers=self.headers)

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

在我调用 sign_in 的情况下,返回一个 key,然后我将其用作请求的 token 。希望这会有所帮助,我也是 Locust 的新手。

关于python - Locustio(Python)登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48645831/

相关文章:

Python:Sklearn.linear_model.LinearRegression 工作异常

python - PyCharm:通过 SSH 配置多跳远程解释器

python - 重新格式化已删除的 Selenium 表

angularjs - 允许 Nginx 上的 CORS 与 AngularJS HTTP GET 配合使用

django - 为什么 Django Rest Framework - 序列化程序验证不起作用

asp.net - 如何使用 python 请求和 BeautifulSoup 在 Aspx 动态网站中循环下拉菜单并抓取数据

python - 将数据框中的列文本与 pandas/python 中的条件相结合

.net - ASP 4.0 IIS HTTP 404

javascript - 单击 <a href =""> 在客户端浏览器请求中添加授权 header

python - 如何抓取 Flipkart 评论中的评论数据 阅读更多内容