python - Locust:我如何仅针对当前 Locust 用户与其余任务共享 auth cookie?

标签 python multithreading task locust taskset

我正在考虑将我的多线程 python 脚本移动到 locust。

我的脚本所做的简单解释是:

  1. 为每个用户创建一个话题
  2. 在每个线程中验证用户并获取auth cookie
  3. 使用该 auth cookie 以设定的时间间隔执行各种 api 调用

当我开始研究 Locust 时,我注意到在其特定时间间隔内执行每项任务的唯一方法是,我需要为每个任务创建一个任务集。

这引发了一个问题,即如何在任务集之间为给定的派生用户共享身份验证 cookie?因为从长远来看,我还需要在给定派生用户的任务集之间共享响应数据,因为它在派生用户之间有所不同。

在下面的示例代码中,locust 生成的所有用户共享同一个“storage.cookie”。有没有办法让每个用户保持 storage.cookie 唯一,并与 locust 给定衍生用户的所有任务集共享它? Locust 是否报告当前正在执行任务的用户?

from __future__ import print_function
from locust import Locust, TaskSet, task, HttpLocust
import json


def auth(l):
    payload = {"username":"some_username","password":"some_password"} 
    resp = l.client.post('/auth', data = json.dumps(payload))
    storage.cookie = # get auth cookie from resp

def do_i_auth(l):
    if len(storage.cookie) == 0:
        auth(l)

class storage(object):
    cookie == ''

class first_call(TaskSet):
    def on_start(self):
        do_i_auth(self)

    @task
    def get_api_a(self):
        headers = {"Cookie":storage.cookie}
        self.client.get('/api_a', headers)

class second_call(TaskSet):
    def on_start(self):
        do_i_auth(self)

    @task
    def get_api_b(self):
        headers = {"Cookie":storage.cookie}
        self.client.get('/api_b', headers)

class api_A(HttpLocust):
    task_set = first_call
    min_wait = 5000
    max_wait = 5000    

class api_B(HttpLocust):
    task_set = second_call
    min_wait = 10000
    max_wait = 10000

最佳答案

您可以尝试让您的授权函数返回 cookie 并将其分别存储在每个类中。像这样:

from __future__ import print_function
from locust import Locust, TaskSet, task, HttpLocust
import json


def auth(l):
    payload = {"username":"some_username","password":"some_password"} 
    resp = l.client.post('/auth', data = json.dumps(payload))
    cookie = # get auth cookie from resp
    return cookie

class first_call(TaskSet):
    cookie = ""

    def on_start(self):
        self.cookie = auth(self)

    @task
    def get_api_a(self):
        headers = {"Cookie":self.cookie}
        self.client.get('/api_a', headers)

关于python - Locust:我如何仅针对当前 Locust 用户与其余任务共享 auth cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48739300/

相关文章:

Objective-C:阻塞线程直到 NSTimer 完成(iOS)

c# - async 和 await 是单线程的真的吗?

c# - IRequestHandler 返回 void

python - 在Python asyncio中创建并发任务之间的依赖关系

python - 使用 Python 估计自相关

python - 如何在 Powershell 应用程序中使用 python 脚本的输出?

multithreading - 当两个线程分别运行一个特定的进程时,一个线程返回值时程序会结束吗?

Java:如何让2个Thread交替使用一个方法

Python 数组到数组的转换

python - 如何获取当前文件目录的完整路径?