首页 > 代码库 > Python 简单的并发访问http

Python 简单的并发访问http

#!/usr/bin/env python

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

# author: Changhua Gong


import time,threading

# from urllib.request import Request, urlopen py3

# from urllib.error import URLError py3

import urllib2


#URL

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

#

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()


本文出自 “90SirDB” 博客,请务必保留此出处http://90sirdb.blog.51cto.com/8713279/1918348

Python 简单的并发访问http