ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Python实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能

2020-03-15 22:40:57  阅读:238  来源: 互联网

标签:Python python 线程 数及 post 多线程


这篇文章主要介绍了Python实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能,涉及Python网络请求的创建、发送、响应、处理等相关操作技巧,需要的朋友可以参考下
本文实例讲述了Python实现可设置持续运行时间、线程数及时间间隔的多线程异步post请求功能。分享给大家供大家参考,具体如下:

#coding=utf8
'''
random.randint(a, b):用于生成一个指定范围内的整数。
其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b
random.choice(sequence):从序列中获取一个随机元素
参数sequence表示一个有序类型(列表,元组,字符串)
'''
import httplib,json
import time
import threading
from random import randint,choice
#创建请求函数
def postRequest(threadNum):
  postJson={
        }
  #定义需要进行发送的数据
  postData=json.dumps(postJson)
  #定义一些文件头
  headerdata = {
    "content-type":"application/json",
     }
  #接口
  requrl ="/v1/query"
  #请求服务,例如:www.baidu.com
  hostServer=""
  #连接服务器
  conn = httplib.HTTPConnection(hostServer)
  #发送请求
  conn.request(method="POST",url=requrl,body=postData,headers=headerdata)
  #获取请求响应
  response=conn.getresponse()
  #打印请求状态
  if response.status in range(200,300):
    print u"线程"+str(threadNum)+u"状态码:"+str(response.status)
  conn.close()
def run(threadNum,internTime,duration):
  #创建数组存放线程
  threads=[]
  try:
    #创建线程
    for i in range(1,threadNum):
      #针对函数创建线程
      t=threading.Thread(target=postRequest,args=(i,))
      #把创建的线程加入线程组
      threads.append(t)
  except Exception,e:
    print e
  try:
    #启动线程
    for thread in threads:
        thread.setDaemon(True)
        thread.start()
        time.sleep(internTime)
    #等待所有线程结束
    for thread in threads:
        thread.join(duration)
  except Exception,e:
      print e
if __name__ == '__main__':
  startime=time.strftime("%Y%m%d%H%M%S")
  now=time.strftime("%Y%m%d%H%M%S")
  duratiion=raw_input(u"输入持续运行时间:")
  while (startime+str(duratiion))!=now:
    run(10,1,int(duratiion))
    now=time.strftime("%Y%m%d%H%M%S")

运行结果:在这里插入图片描述

写到这里,给大家推荐一个资源很全的python学习聚集地,点击进入,这里有资深程序员分享以前学习

心得,学习笔记,还有一线企业的工作经验,且给大家精心整理一份python零基础到项目实战的资料,

每天给大家讲解python最新的技术,前景,学习需要留言的小细节

标签:Python,python,线程,数及,post,多线程
来源: https://blog.csdn.net/haoxun11/article/details/104886979

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有