安装(使用国内源安装):
pip3 install -i https://pypi.doubanio.com/simple/ --trusted-host pypi.doubanio.com locust
简单脚本
# coding=utf-8
import requests
from locust import HttpUser,TaskSet,task,HttpUser,between
from requests.packages.urllib3.exceptions import InsecureRequestWarning
# 禁用安全请求警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class MyBlogs(TaskSet):
# 访问我的博客首页
# @task(1)
def get_blog(self):
# 定义请求头
header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36"}
req = self.client.get("/imyalost", headers=header, verify=False)
if req.status_code == 200:
print("success")
else:
print("fails")
@task(1)
def test_one(self):
a = self.user.sum_value(self.user.value)
self.user.value = a
print(a)
class websitUser(HttpUser):
tasks = [MyBlogs]
host = "https://www.cnblogs.com"
# min_wait = 1000 # 单位为毫秒,不推荐使用,我使用时失效了
# max_wait = 2000 # 单位为毫秒,不推荐使用,我使用时失效了
wait_time = between(1,2)
value = 0
def sum_value(self,value):
value+=1
return value
if __name__ == "__main__":
import os
os.system("locust -f locustfile.py --host=https://www.cnblogs.com")
wait_time 设置用户每次请求等待区间
访问页面执行(页面开始无法自动停止)
自动停止使用终端进行运行locust
locust -f locustfile.py --headless -u 1 -r 1 -t 1s
--headless 相当于无页面
-u 虚拟用户数
-r 每秒启动用户数
-t 脚本执行时间
--master 设置主机
--expect-workers=1 等待从机,1为数量
--worker 配置从机
--master-host 配置从机对应主机的ip