文章目錄
通常我们写好一个接口后,需要做接口性能测试,知道接口的QPS(Queries Per Second),百分位响应时间,我们可以用Python库Locust来做
pip install locust库后,新建locustfile.py,写入要测试的接口,demo如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| from locust import HttpUser, task, between import json
class MyUser(HttpUser): wait_time = between(1, 2)
@task def post_request(self):
url = 'https://www.baidu.com'
payload = { "url": url, } headers = { "Content-Type": "application/json" }
with self.client.post('http://%s/api/generate_cookies' % '127.0.0.1:5009', json=payload, headers=headers, catch_response=True) as response: if response.status_code == 200: try: response.success() except ValueError: response.failure("Response is not valid JSON") else: response.failure(f"Status code: {response.status_code}")
|
locust -f locustfile.py –web-port=8089,之后浏览器里打开 http://localhost:8089/ 就可以新建一个测试
测试结果中,RPS就是我们常说的QPS,95%ile 指的是 95百分位响应时间 (Percentile Response Times),也就是95%的请求的响应时间不超过某个值。