简体   繁体   中英

How to run a uvicorn server (using FastAPI) and a load test (using locust) parallely?

I have two files, both of them runs individually without any error. I used FastAPI to create some endpoints and I am trying to use locust (through a tool invokust from FutureSharks ) to perform load testing.

In my file run_server.py I have the following code

from main import app
import uvicorn

if __name__ == "__main__":
   uvicorn.run(app, host="127.0.0.1", port=8000)

In my file load_test.py I have the following code

import invokust

settings = invokust.create_settings(
        locustfile='locustfile.py',
        host='http://127.0.0.1:8000',
        num_users=1,
        spawn_rate=1,
        run_time='1m'
    )

loadtest = invokust.LocustLoadTest(settings)
loadtest.run()
loadtest.stats()
"{'requests': {'GET_/': {'request_type': 'GET', 'num_requests': 923, 'min_response_time': 113.54585000000128, 'median_response_time': 120.0, 'avg_response_time': 145.68631223510297, 'max_response_time': 331.89674199999786, 'response_times': {270.0: 2, 120.0: 479, 150.0: 17, 200.0: 83, 210.0: 80, 160.0: 20, 190.0: 55, 220.0: 9, 130.0: 30, 170.0: 22, 230.0: 5, 110.0: 69, 140.0: 19, 180.0: 27, 240.0: 2, 320.0: 3, 330.0: 1}, 'response_time_percentiles': {55: 120.0, 65: 150.0, 75: 190.0, 85: 200.0, 95: 210.0}, 'total_rps': 5.136500841568583, 'total_rpm': 308.190050494115}, 'GET_/about': {'request_type': 'GET', 'num_requests': 308, 'min_response_time': 113.23035299999873, 'median_response_time': 120.0, 'avg_response_time': 146.04534828246747, 'max_response_time': 290.40608500000076, 'response_times': {120.0: 147, 200.0: 36, 190.0: 25, 110.0: 27, 160.0: 12, 150.0: 6, 180.0: 13, 210.0: 12, 170.0: 13, 220.0: 2, 130.0: 8, 140.0: 6, 290.0: 1}, 'response_time_percentiles': {55: 120.0, 65: 160.0, 75: 180.0, 85: 200.0, 95: 200.0}, 'total_rps': 1.7140219492991589, 'total_rpm': 102.84131695794953}}, 'failures': {}, 'num_requests': 1231, 'num_requests_fail': 0, 'start_time': 1608207776.312684, 'end_time': 1608207956.070369}"

I want to run them parallely, so when my run_server.py starts the uvicorn server, my load_test.py starts doing the load testing.

How can I do this ?

i hope it'll help you

from main import app
import uvicorn
import load_test

@app.on_event("startup")
async def startup():
    load_test.load_test.run()

if __name__ == "__main__":
   uvicorn.run(app, host="127.0.0.1", port=8000)

notice: make sure your ports are not be same number

for example : fastapi > port=8000 and invokust > port=8001

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM