python 的接口并发库 grequests
requests库是个串行库,grequests库是并行库。把请求放到列表中,一起发送,返回的也是一个列表
下面做个实验;
先用requests进行对一个接口的100次访问:
import requests import time start = time.time() res_list = [requests.get('http://127.0.0.1:8000/api/t/') for i in range(100)] print(time.time()-start)
执行时间是2.5857s
再用grequests库进行对一个接口的100次访问呢:
import grequests import time start = time.time() req_list = [grequests.get('http://127.0.0.1:8000/api/t/') for i in range(100)] res_list = grequests.map(req_list) print(time.time()-start)
执行时间是1.807s
测试员可以哪来问并发测试, grequests也是可以支持很多的请求方式的
# Shortcuts for creating AsyncRequest with appropriate HTTP method
get = partial(AsyncRequest, 'GET')
options = partial(AsyncRequest, 'OPTIONS')
head = partial(AsyncRequest, 'HEAD')
post = partial(AsyncRequest, 'POST')
put = partial(AsyncRequest, 'PUT')
patch = partial(AsyncRequest, 'PATCH')
delete = partial(AsyncRequest, 'DELETE')
可以指定报错执行的处理函数 用exception_handler参数指定函数,gtimeout整体指定超时时间,timeout 单独指定超时时间
import grequests def err_handler(request, exception): print("请求出错") req_list = [ grequests.post('http://127.0.0.1:8000/api/t/',json={"Staff_name":"张三","Staff_username":"cs ","Staff_phone":"张三","Staff_mailbox":"张三"}, timeout=1), grequests.get('http://127.0.0.1:8000/api/mo/'), grequests.get('http://127.0.0.1:8000/api/api/') ] res_list = grequests.map(req_list, exception_handler=err_handler,gtimeout=2) for i in res_list: print(i.text )
挖掘一下还是有点意思的