Python 簡單的併發訪問http

#!/usr/bin/env pythonpython

# -*- coding:utf-8 -*-web

# author: Changhua Gong併發


import time,threadingide

# from urllib.request import Request, urlopen py3url

# from urllib.error import URLError py3線程

import urllib2code


#URLserver

req = urllib2.Request('http://47.93.169.69:10080/pigeon-web/user/userExtraInfo?userId=1')utf-8

#get

rule = {0:500,1:30}

'''

Rule規則:0:50,第一次運行不睡眠即爲0,直接併發50次;1:20,第二秒,至關於睡眠1秒,而後併發20次,

如第三秒需併發500次,則rule = {0:50,1:20,1:500}

'''

#Open url

def geturl():

    time_b = time.time()

    try:

        response = urllib2.urlopen(req)

        print(response.read().decode("utf-8"))  # 打印輸出內容

    except urllib2.URLError as e:

        if hasattr(e, 'reason'):

            print('We failed to reach a server.')

            print('Reason: ', e.reason)

        elif hasattr(e, 'code'):

            print('The server couldn\'t fulfill the request.')

            print('Error code: ', e.code)

    time_e = time.time()

    print("Thread %s runned for %ss" % (threading.current_thread().name, (time_e - time_b)))  #線程訪問時效


if __name__=='__main__':

    for k in rule:

        time.sleep(k)

        for i in range(rule[k]):

            t = threading.Thread(target=geturl)

            t.start()

相關文章
相關標籤/搜索