多线程调用一个接口,使用 threading

#!/user/bin/env python
#coding=utf-8
import requests
import datetime
import time
import threading

class url_request():
    times = []
    error = []
    def req(self):#请求首页接口
        myreq=url_request()
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',
            'Referer': 'http://test.m.ncfimg.com/',
            'XHTK':'pnzwrw1atkdms11ze5sj1ttkpbl1d6l0tn'
        }
        #payload = {'reqtoken': 'de6df8d7bd8b7a1c99caa0b9743075e8ddbe8082e20f290fa344247a89d2dd8f'}
        r = requests.post("http://test.api.ncfimg.com/nmvapi/index/index",headers=headers)
        ResponseTime=float(r.elapsed.total_seconds())*1000 #获取响应时间,单位ms
        myreq.times.append(ResponseTime) #将响应时间写入数
        if r.status_code !=200 :
            myreq.error.append("0")
        with open('threads_result','a') as f:
            f=f.write(str(r.status_code)+'\n')
        print(ResponseTime)


class Thread_out():
    def __init__(self):
        global nub
        nub=1 # 设置并发线程数
    def threads(self):
        myreq = url_request()
        threads = []
        starttime = datetime.datetime.now()
        print("请求开始时间: %s" % starttime)
        #nub = 2  # 设置并发线程数
        ThinkTime = 0  # 设置思考时间
        for i in range(1, nub + 1):
            t = threading.Thread(target=myreq.req, args=())
            threads.append(t)
        for t in threads:
            time.sleep(ThinkTime)
            # print "thread %s" %t #打印线程
            t.setDaemon(True)
            t.start()
        t.join()
        endtime = datetime.datetime.now()
        print("请求结束时间: %s" % endtime)
        time.sleep(0)
        AverageTime = "{:.3f}".format(float(sum(myreq.times)) / float(len(myreq.times)))  # 计算数组的平均值,保留3位小数
        print("平均响应时间: %s ms" % AverageTime)  # 打印平均响应时间
        usetime = str(endtime - starttime)
        hour = usetime.split(':').pop(0)
        minute = usetime.split(':').pop(1)
        second = usetime.split(':').pop(2)
        totaltime = float(hour) * 60 * 60 + float(minute) * 60 + float(second)  # 计算总的思考时间+请求时间
        print("并发数量: %s" % nub)  # 打印并发数
        print("总消耗时间: %s s" % (totaltime - float(nub * ThinkTime)))  # 打印总共消耗的时间
        print("错误请求数: %s" % myreq.error.count("0"))  # 打印错误请求数

if __name__=='__main__':
    t=Thread_out()
    t.threads()

你可能感兴趣的:(python)