Reputation: 2821
I found out the Locust UI would fetch data from http://my-locust-server/stats/requests
endpoint, and plot the chart. e.g. Total request per Second
, Response Time
and Number of Users
.
I would like to send the /stats/requests
data to another server for plotting purpose. How to do that in locustfile.py
?
Following codes won't work, just for demo purpose.
from locust import HttpUser, task, events
import requests
class User(HttpUser):
@task
def scenario_01(self):
self.client.get('/some_endpoint')
# ==========
# following codes won't work, will block the whole locust.
# ==========
import time
starttime = time.time()
while True:
r = requests.get('http://my-locust-server/stats/requests')
payload = r.json()
requests.post('http://another-server-for-plotting', json=payload)
time.sleep(5.0 - ((time.time() - starttime) % 5.0))
Now what I can think of is to run another program to fetch and report the data. But how to do that in one locustfile.py
.
Thanks!
Upvotes: 0
Views: 1039
Reputation: 2866
Alternatively, you can use Locust's Event Hooks to send data off directly without getting it from the web route. If you're running in distributed mode, worker_report
would probably be best. Incomplete example:
from locust import events
import requests
@events.worker_report.add_listener
def send_data_off_somewhere(client_id, data):
requests.post('http://another-server-for-plotting', json=data)
locust-plugins has good examples about how to use the events and even has a pre-built listener to ship data off directly to a timescale db.
Upvotes: 1
Reputation: 6554
When this module is imported, the while True
code will be evaluated and run forever. If you want that loop to run in the background, you could utilize the python threading library. Put that while loop inside a callable function, and pass that function to a new Thread object and start the thread on import.
from locust import HttpUser, task, events
import requests
class User(HttpUser):
@task
def scenario_01(self):
self.client.get('/some_endpoint')
def backgroundloop():
while True:
import time
starttime = time.time()
r = requests.get('http://my-locust-server/stats/requests')
payload = r.json()
requests.post('http://another-server-for-plotting', json=payload)
time.sleep(5.0 - ((time.time() - starttime) % 5.0))
import threading
t = threading.Thread(target=backgroundloop)
t.start()
Upvotes: 1