今天给大家分享一下python中的多线程技术,可能有同学就在想了,我们为什么要学习多线程技术呢,因为啊在我们平时直接脚本时当用例较多时可能脚本执行的时间很久,这时我们就可以使用多线程技术,这里可以大大减少脚本执行的时间。
好了,废话不多说,直接上代码,这里博主写了两个比较简单的接口自动化测试的例子,这里呢博主只会讲一下最常用的几个方法,想深入了解的小伙伴可以参考网上的相关文档。
from time import sleep,ctime
import requests
import threading
class Requestuil:
def __init__(self):
pass
def request(self,url,method,headers=None,param=None,content_type=None):
'''请求工具类封装'''
try:
if method == "get":
result = requests.get(url=url,params=param,headers =headers).json()
return result
elif method == "post":
if content_type == "application/json":
result = requests.post(url=url,json=param,headers = headers).json()
return result
else:
result = requests.post(url = url,data=param,headers=headers).json()
return result
else:
print('只做了post and get请求')
except Exception as e:
print("http请求报错:{0}".format(e))
if __name__ == '__main__':
r = Requestuil()
url = 'http://app.ppmbook.com/book/addHeat.do'
heard = {'token':'d57c1c60e6709396382c9a5e3652075674054e6ee4cc6f8db407b5ec64ae34c810a07b61b15b6554d449de10df4bb1fb',
'oid':'01fe710d81d3439aabbcda4483f607fc'}
param = {'inParam':'{"mediumId":7665,"oid":"01fe710d81d3439aabbcda4483f607fc"}'}
'''播放一百次测试'''
def play():
for i in range(100):
print(r.request(url=url,method='post',headers=heard,param=param))
sleep(1)
urlxq = 'http://app.ppmbook.com/book/viewBookNew.do'
'''查看详情页100次测试'''
def details():
for i in range(100):
print(r.request(url=urlxq,method='post',headers=heard,param=param))
sleep(1)
threads = []
t1 = threading.Thread(target=play)
threads.append(t1)
t2 = threading.Thread(target=details)
threads.append(t2)
for t in threads:
t.start()
for t in threads:
t.join()
这是一个直接可以运行的例子,上面很多关于requests库的的方法这里就不重复讲了
import threading:引入线程组模块
threads = []:创建线程组用于装载线程
threading.Thread():通过调用threading模块的Thread()方法来创建线程。Thread()可以加入参数target=需要加入线程的方法名、args=该方法需要传入的实参没有则不写。
通过for循环遍历threads数组中所装载的线程,start()开始线程活动,join()等待线程终止。
看,两个线程是同步执行的,这样可以大大减少代码执行的时间