码迷,mamicode.com
首页 > 编程语言 > 详细

Python 简单的并发访问http

时间:2017-04-21 21:48:57      阅读:206      评论:0      收藏:0      [点我收藏+]

标签:python   urllib   urllib2   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

标签:python   urllib   urllib2   http   

原文地址:http://90sirdb.blog.51cto.com/8713279/1918348

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!