import asyncio
import sys
from queue import Queue

sys.path.append("../")
from tool.__init__ import *
from tool.decorator_token import *
import time
from threading import Thread,Lock

class doWeChatNotify(BaseTest):
def __init__(self):
super().__init__()
self.limit_num=100 #查询记录条数
self.WeChatNotify_sql='''select order_id,order_sn from fw_order where `status`=0
and course_id=1569 ORDER BY create_time desc limit %d ;'''%(self.limit_num)
self.fwh_test_api=fwh_test_api
self.data = self.my_op.sql_operation_fwh(self.WeChatNotify_sql)
self.fwh_order_dict = {}
self.que = Queue()

@token_fwh#验证token有效性
def get_fwh_token_list(self):
token_list=self.fwh_token.loadTokenList()
return token_list

@token_crm#验证token有 def get_crm_token_list(self) token_list=self.token.loadTokenList()
        return token_list

def testDoWeChatNotify(self):
DoWeChatNotify_file='../tokenFileAndtxtFiles'+'/'+"DoWeChatNotify_asynchronousPay.txt"
with open(DoWeChatNotify_file,'a',encoding='utf=-8') as file:
str_first="order_id\t"+"order_sn\t\n" #文件首行数据
file.write(str_first)
fwh_order_id_list, fwh_order_sn_list = [], []

if self.data!=():
for a in self.data:
fwh_order_id=a['order_id']
fwh_order_sn=a['order_sn']
self.fwh_order_dict[fwh_order_id]=fwh_order_sn

with open(DoWeChatNotify_file,'a',encoding='utf-8') as file2:#文件写入
str_DoWeChatNotifyInfo=str(fwh_order_id)+'\t'+str(fwh_order_sn)+'\t\n'
file2.flush() #清除缓冲区
file2.write(str_DoWeChatNotifyInfo)
self.que.put(self.fwh_order_dict)#将数据添加至队列
#关闭数据库连接
# self.my_op.close_db_fwh()
# self.my_op.close_db()
return self.que.qsize()#返回队列数量

def asynchronousPay(self,order_id,order_sn):
count=1
count_num=50
token_list=self.get_fwh_token_list()
if (self.data!=()):
headers_form_urlencoded['token']=token_list[0]
url_wechat_success_huidiao=self.fwh_test_api+'/index/Order/doWeChatNotify'
data_wechat_success_huidiao=self.data_to_str.requestDataToStr_firefoxAndChrome_fwh('''order_sn:{}
order_id:{}
meth_id:4
timestamp:157129653969
sign:0687b01b300b9e300d3996a9d2173f1380973e5a'''.format(order_sn,order_id))
request_wechat_success_huidiao=requests.post(url=url_wechat_success_huidiao,headers=headers_form_urlencoded,data=data_wechat_success_huidiao)
response_wechat_success_huidiao=request_wechat_success_huidiao.json()
if '订单状态错误,非待支付订单' in response_wechat_success_huidiao['msg']:
print(data_wechat_success_huidiao)
else:
print('待支付订单为空')

def run_multithreading(self):#多线程
threads = []#存放所有的线程
nloops = list(range(self.testDoWeChatNotify()))#获取队列数量
if len(nloops)>0:
for i,k in zip(nloops,self.que.get().items()):#根据队列数量来创建线程
t = Thread(target=self.asynchronousPay,args=(k[0],k[1]))
threads.append(t)

for s in nloops: # 开始多线程
threads[s].start()

for j in nloops: # 等待所有线程完成
threads[j].join()

else:
print("队列数量为空")

if __name__=="__main__":
start_time = time.time() # 计算程序开始时间
wechfy=doWeChatNotify()
wechfy.run_multithreading()#多线程
print('程序耗时{:.2f}'.format(time.time() - start_time)) # 计算程序总耗时

思路:
  队列使用说明:
      multiprocessing.Queue()#用于进程间通信,单主进程与子进程无法通信(使用进程池时尽量不要使用这个)
      multiprocessing.Manager().Queue()#用于主子进程通信,通过进程池(pool)创建的进程可以数据共享
      queue.Queue()#用于线程间通信,同一进程内的数据可以共享
  1.从数据库里获取待支付的订单
  2.将获取出来的数据添加至队列(queue.Queue()),并在函数中返回消息队列的长度
  3.根据队列长度创建对应的线程数量
  4.把创建的线程放在list
  5.依次启动
  6.最后等待主线程执行完结束,统计函数运行时长
总结:亲测运行时间还是会快很多,单线程支付100个订单四十几秒的样子,多线程运行不用join2.x秒,用join八秒的样子,还有很大的优化空间,因为运行时会创建100个线程
求大佬指教,最近想用多线程或者多进程做并发测试

ps: 最近看了下文章,发现python中是这么定义多线程与多进程的使用场景的,cpu密集型(复杂计算)程序适合多进程处理,io密集型(写文件、网络请求等)程序适合多线程处理

python多线程完成模拟支付请求的更多相关文章

  1. python模拟http请求

    下文主要讲述如何利用python自带的库模拟http请求,为以后利用python做API测试做准备. 只讲述模拟http的过程,具体到自己用的时候,要以自己的应用为准做出适当的调整. #!coding ...

  2. python模拟Get请求保存网易歌曲的url

    python模拟Get请求保存网易歌曲的url 作者:vpoet mail:vpoet_sir@163.com 日期:大约在夏季 #coding:utf-8 import requests impor ...

  3. 第五十九节,模拟浏览器请求Python结合html基本格式

    模拟浏览器请求Python结合html基本格式 用Python模拟一个客户端,结合打开一个HTML页面 创建客户端 #!/usr/bin/env python # -*- coding:utf8 -* ...

  4. python利用requests库模拟post请求时json的使用

    我们都见识过requests库在静态网页的爬取上展现的威力,我们日常见得最多的为get和post请求,他们最大的区别在于安全性上: 1.GET是通过URL方式请求,可以直接看到,明文传输. 2.POS ...

  5. Python数据库访问公共组件及模拟Http请求

    前言 最近一段时间除了忙于工作之外,在业余时,迷上了python,对它的跨平台深深的吸引.经过一段时间的自我学习,了解了其基本的语法,便开始自己着手摆弄起来.主要想把以前对接的接口再实现一次,以便于在 ...

  6. python入门常用方法(转json,模拟浏览器请求头,写入文件)

    转json import jsonjson = json.loads(html) 模拟浏览器请求头 import urllib.request req = urllib.request.Request ...

  7. 教你如何用Python模拟http请求(GET,POST)

    模拟http请求有什么用呢? 我们现在使用的所有需要使用网络的:软件 应用 app 网站里面的绝大部分功能都是通过http协议来工作的 什么是http协议? http协议,超文本传输协议(HTTP,H ...

  8. python模拟http请求2

    发现了一个非常好用的第三方module:requests,模拟接口非常简单. 详细了解请移步:http://docs.python-requests.org/en/latest/ 非常不错 #!cod ...

  9. Python爬虫3-parse编码与利用parse模拟post请求

    GitHub代码练习地址:①利用parse模拟post请求:https://github.com/Neo-ML/PythonPractice/blob/master/SpiderPrac04_pars ...

  10. python get post模拟请求

    1.使用get方式时.url相似例如以下格式: &op=bind   GET报问头例如以下: &n=asa HTTP/1.1    Accept: */*    Accept-Lang ...

随机推荐

  1. 机器人的运动控制是否可以引入生物学信息,生物学信息是否可以辅助机器人的智能控制算法的训练:《Robotic prosthetic ankles improve 'natural' movement, stability》

    相关内容: Robotic prosthetic ankles improve 'natural' movement, stability 看了上面的论文的介绍(内容没看到,不是open access ...

  2. 强化学习中经验池的替代设计——A3C算法

    读论文<Asynchronous methods for deep reinforcement learning>有感 ---------------------------------- ...

  3. Ubuntu18.04 系统环境下 vscode中忽略pylint某些错误或警告

    相关: ubuntu18.04系统环境下使用vs code安装pylint检查python的代码错误 ====================================== 假设已经在前文(ht ...

  4. 网络问题解决:Ubuntu连接局域网中Windows主机上的v2r报错:rejected core/proxy/socks: unknown Socks version: 67

    参考: https://github.com/2dust/v2rayN/issues/3916 https://www.eolink.com/news/post/30941.html ======== ...

  5. 分布式深度学习计算框架依赖环境——NCCL的安装

    分布式深度学习计算框架(MindSpore, PyTorch)依赖环境--NCCL, NCCL提供多显卡之间直接进行数据交互的功能(可以跨主机进行). 注意: 本文环境为  Ubuntu18.04 以 ...

  6. Java实现微信登录(网页授权)

    1.背景 实际开发中,使用第三方登录是非常常见的业务... 这样可以大提高用户体验,没必要一来就要注册,或者登录之类的... 并且开发一个登录或者注册严格来说也是非常麻烦的(各种防止攻击.机器操作等) ...

  7. centos 7 安装 flask

    最近 Python 特别火,尤其是在人工智能和大数据分析方面,更是如火如荼.正好放假有空就简单看了下Python 先从熟悉的地方入手,那就从web框架开始学学吧. 首先,官方给了安装方法:http:/ ...

  8. 秒懂全文:盘点13个各具特色的AI智能阅读助手工具

    在当今信息爆炸的时代,AI阅读工具正在革新我们的阅读方式,成为了提高效率.优化阅读体验的关键. 这类AI阅读辅助工具,只需要上传文件或者输入链接,便可以直接以聊天对话的形式进行一键总结和智能问答,满足 ...

  9. 018.CentOS升级内核

    一 更新yum源 1 [root@localhost ~]# rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org 2 [root@lo ...

  10. 8. 从0学ARM-内联汇编、混合汇编、ATPCS规则

    一.gcc 内联汇编 内联汇编即在C中直接使用汇编语句进行编程,使程序可以在C程序中实现C语言不能完成的一些工作,例如,在下面几种情况中必须使用内联汇编或嵌入型汇编. 程序中使用饱和算术运算(Satu ...