python性能测试locust
测试服务端:
from flask import Flask,request
app = Flask(__name__)
@app.route("/login", methods=['POST'])
def login():
if 0:
username = request.form.get('username')
password = request.form.get('password')
else:
data = request.json
username = data.get('username')
password = data.get('password')
if username == 'test' and password == 'pass':
return 'OK'
else:
return "FAILED"
@app.route("/products")
def products():
product = {
'id':1,
'name': '商品',
'price': 23.22
}
return [product, product, product]
@app.route("/product/1")
def product():
product = {
'id':1,
'name': '商品',
'price': 23.22
}
return product
if __name__ == "__main__":
app.run()
测试脚本 locustfile1.py :
from locust import HttpUser,task,between,TaskSet
class WebsiteUser(HttpUser):
# 请求间等待时间1-3秒(模拟用户思考时间)
wait_time = between(1,3)
# 每个用户启动时执行(用于登录等操作)
def on_start(self):
self.client.post("/login", json={"username":"test","password":"pass"})
# 权重为3,执行频率高
@task(3)
def browse_products(self):
self.client.get("/products")
# 权重为1,执行频率较低
@task
def view_detail(self):
self.client.get("/product/1")
执行命令:
启动服务:
python server.py
* Serving Flask app 'server'
* Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
* Running on http://127.0.0.1:5000
Press CTRL+C to quit
127.0.0.1 - - [21/Jul/2025 18:52:51] "GET /product/1 HTTP/1.1" 200 -
127.0.0.1 - - [21/Jul/2025 18:52:51] "GET /product/1 HTTP/1.1" 200 -
127.0.0.1 - - [21/Jul/2025 18:52:51] "GET /product/1 HTTP/1.1" 200 -
启动模拟脚本
locust -f locustfile1.py --host=http://127.0.0.1:5000
[2025-07-21 18:48:09,532] xuxb/INFO/locust.main: Starting Locust 2.37.14
[2025-07-21 18:48:09,532] xuxb/INFO/locust.main: Starting web interface at http://localhost:8089, press enter to open your default browser.
=== Test started ===
[2025-07-21 18:48:14,550] xuxb/INFO/locust.runners: Ramping to 1 users at a rate of 1.00 per second
[2025-07-21 18:48:14,550] xuxb/INFO/locust.runners: All users spawned: {"WebsiteUser": 1} (1 total users)
[2025-07-21 18:49:10,115] xuxb/INFO/locust.runners: Ramping to 50 users at a rate of 1.00 per second
[2025-07-21 18:49:55,787] xuxb/INFO/locust.runners: All users spawned: {"WebsiteUser": 50} (50 total users)
⚠️ Slow request detected: /products took 2004.729899999802ms
⚠️ Slow request detected: /products took 2005.1908000023104ms
⚠️ Slow request detected: /products took 2004.752599998028ms
⚠️ Slow request detected: /products took 2008.4557999944082ms
⚠️ Slow request detected: /products took 2006.2850000031176ms
压测结果:
打开:http://localhost:8089/

参考:https://blog.csdn.net/weixin_40123451/article/details/118709125
本文来自博客园,作者:河北大学-徐小波,转载请注明原文链接:https://www.cnblogs.com/xuxiaobo/p/18996364

浙公网安备 33010602011771号