python学习笔记(threading多线程)

博主昨天优化了接口框架想着再添加些功能

想到对接口的性能压力测试

在工作过程中之前都是使用的工具 如:loadrunner、jmeter

想着这次准备用python实现对接口的性能压力测试

首先要实现这个功能就要运用到python的threading模块 

下面是自己学习摸索出来的代码:

 1 #!/usr/bin/env python
 2 # -*- coding: utf_8 -*-
 3 
 4 import threading
 5 import requests
 6 from time import ctime
 7 
 8 
 9 def api(url, data):
10     try:
11         r = requests.post(url, data)
12         print "接口访问返回状态码: ", r.status_code
13         print "接口请求时间: ", ctime()
14         print "接口访问返回地址: ", r.url
15     except Exception.__bases__:
16         print "接口访问失败 ", "接口请求时间: ", ctime()
17 
18 case_1 = {'username': 'admin', 'password': '123456'}
20 url1 = 'http://localhost:8081/swcw/back/sysLogin.action'
21 
22 
23 threads = []
24 for i in range(10):
25     t_i = threading.Thread(target=api(url1, case_1))
26     threads.append(t_i)
27 
28 if __name__ == '__main__':
29     for t in threads:
30         t.setDaemon(True)
31         t.start()
32     t.join()
33 
34     print "all over %s" % ctime()

这个是10个进程同时登录的场景

之后要改成类的形式 增加一些性能运行的结果数据

最后我推荐一位关于多线程的博客 通俗易懂

博主自己也是从上面学习的

http://www.cnblogs.com/fnng/p/3670789.html

原文地址:https://www.cnblogs.com/cllovewxq/p/5398021.html