import asyncio
import sys
from queue import Queue sys.path.append("../")
# from tool.__init__ import *
from tool.Common import *
from tool.tencent_cloud_mysql_connect import Mysql_operation
from tool.request_data_change_to_StrEncode import request_data_change_to_str
import time
import gevent
import asyncio
import aiohttp#requests异步版 class doWeChatNotify(object):
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.WeChatNotify_sql ='''select order_id,order_sn from order_info limit 500;'''
self.fwh_test_api=fwh_test_api
self.my_op=Mysql_operation()
self.data = self.my_op.sql_operation(self.WeChatNotify_sql)
self.data_to_str=request_data_change_to_str()
self.fwh_order_dict = {}
self.que = Queue() 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)#将数据添加至队列
return self.que.qsize()#返回队列数量 async def asynchronousPay(self,order_id,order_sn):
if (self.data!=()):
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))
async with aiohttp.ClientSession() as session:
async with session.post(url=url_wechat_success_huidiao,
headers=headers_form_urlencoded,
data=data_wechat_success_huidiao) as response:
await asyncio.sleep(1)
return await response.read() else:
print('待支付订单为空') async def run(self):
self.testDoWeChatNotify() # 获取队列数量
order_id = asyncio.Semaphore(500) # 限制并发量为500
to_get = [self.asynchronousPay(order_id,order_sn) for order_id,order_sn in self.que.get().items()] # 总共1000任务
# threads = [gevent.spawn(self.asynchronousPay, order_id, order_sn) for order_id, order_sn in
# self.que.get().items()]
# gevent.joinall(threads)#gevent协程写法
await asyncio.wait(to_get) def run_startAll(self):
loop = asyncio.get_event_loop()
loop.run_until_complete(self.run())
loop.close() if __name__=="__main__":  
start_time = time.time() # 计算程序开始时间
wechfy=doWeChatNotify()
wechfy.run_startAll()
print('程序耗时{:.2f}'.format(time.time() - start_time)) # 计算程序总耗时

总结:
  1.使用协程请求需用到aiohttp这个库(我把它理解成是requests的异步版本),如果直接用requests这个库去请求则就不能发挥协程的优势(涉及到io操作)或者直接说不能称为了真正的协程;
  2.async/awiat关键字的使用:配合asyncio模块一起使用(结合aiohttp)
  3.执行500个订单的时间为11.x秒,跟多线程执行差不多(但是这个对系统的开销会小很多)
 

python使用协程完成批量模拟支付的更多相关文章

  1. Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就绪,挂起,运行) ,***协程概念,yield模拟并发(有缺陷),Greenlet模块(手动切换),Gevent(协程并发)

    Python进阶----异步同步,阻塞非阻塞,线程池(进程池)的异步+回调机制实行并发, 线程队列(Queue, LifoQueue,PriorityQueue), 事件Event,线程的三个状态(就 ...

  2. {python之协程}一 引子 二 协程介绍 三 Greenlet 四 Gevent介绍 五 Gevent之同步与异步 六 Gevent之应用举例一 七 Gevent之应用举例二

    python之协程 阅读目录 一 引子 二 协程介绍 三 Greenlet 四 Gevent介绍 五 Gevent之同步与异步 六 Gevent之应用举例一 七 Gevent之应用举例二 一 引子 本 ...

  3. python的协程和_IO操作

    协程Coroutine: 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行. 注意,在一个子程序中中断,去执行其他子程序,不是函数调用,有点 ...

  4. python gevent 协程

    简介 没有切换开销.因为子程序切换不是线程切换,而是由程序自身控制,没有线程切换的开销,因此执行效率高, 不需要锁机制.因为只有一个线程,也不存在同时写变量冲突,在协程中控制共享资源不加锁,只需要判断 ...

  5. 深入理解Python中协程的应用机制: 使用纯Python来实现一个操作系统吧!!

    本文参考:http://www.dabeaz.com/coroutines/   作者:David Beazley 缘起: 本人最近在学习python的协程.偶然发现了David Beazley的co ...

  6. 关于Python的协程问题总结

    协程其实就是可以由程序自主控制的线程 在python里主要由yield 和yield from 控制,可以通过生成者消费者例子来理解协程 利用yield from 向生成器(协程)传送数据# 传统的生 ...

  7. 【Python】协程

    协程,又称微线程,纤程.英文名Coroutine. 协程的概念很早就提出来了,但直到最近几年才在某些语言(如Lua)中得到广泛应用. 子程序,或者称为函数,在所有语言中都是层级调用,比如A调用B,B在 ...

  8. Python之协程(coroutine)

    Python之协程(coroutine) 标签(空格分隔): Python进阶 coroutine和generator的区别 generator是数据的产生者.即它pull data 通过 itera ...

  9. python 3 协程函数

    python 3 协程函数 1:把函数的执行结果封装好__iter__和__next__,即得到一个迭代器 2:与return功能类似,都可以返回值,但不同的是,return只能返回一次值,而yiel ...

  10. Python之协程函数

    Python之协程函数 什么是协程函数:如果一个函数内部yield的使用方法是表达式形式的话,如x=yield,那么该函数成为协程函数. def eater(name): print('%s star ...

随机推荐

  1. 并行化强化学习 —— 初探 —— 并行reinforce算法的尝试 (上篇:强化学习在多仿真环境下单步交互并行化设计的可行性)

    强化学习由于难收敛所以训练周期较长,同时由于强化学习在训练过程中起训练数据一般都为实时生成的,因此在训练的同时算法还需要生成待训练的数据,强化学习算法的基本架构可以视作下图:(取自:深度学习中使用Te ...

  2. 在深度计算框架MindSpore中如何对不持续的计算进行处理——对数据集进行一定epoch数量的训练后,进行其他工作处理,再返回来接着进行一定epoch数量的训练——单步计算

    如题所述: 深度学习框架MindSpore是华为公司研发的,由于性能设计的原因,MindSpore的一些使用方式和TensorFlow和PyTorch有一些不同,其中的一点就是在进行单步计算或者是非持 ...

  3. 【转载】手动DIY制作机械臂

    相关链接: https://news.cnblogs.com/n/703664/ https://www.bilibili.com/video/BV12341117rG https://www.cnb ...

  4. .NET 高效开发Nuget管理工具(开源)

    我们.NET开发会引用很多外部Nuget包,多项目.多个解决方案.甚至多个仓库. 简单的Nuget包管理,通过VS就能比较简单处理好.但复杂的场景呢,比如: 1.一个仓库里,有多个解决方案的Nuget ...

  5. 离线安装python包

    1.制作requirement.txt pip freeze > requirements.txt 2.离线下载安装包 #下载单个离线包 pip download -d your_offline ...

  6. Vue状态管理库Pinia详解

    Pinia 是 Vue 的状态管理库,它提供了一种更简单.更不规范的 API 来管理应用的状态.Pinia 的设计哲学是简单性和易用性,它避免了 Vuex 中的许多复杂概念,如 mutations 和 ...

  7. 动态规划专题--容斥原理--codeforces-285E Positions in Permutations

    codeforces-285E \(Positions \ in \ Permutations\) $$codeforces$$ 题意 给定一个序列长度为 \(n\) 的序列 , \(A=\{1 \d ...

  8. WinForm UI 库

    WinForm UI库 HZH_Controls HZHControls是基于.Net Framework4.0原生控件开发完全开源的一套控件,你不需要担心有其他控件或版权问题.提供完整的示例代码,方 ...

  9. CEIT算法训练-双指针部分题解(全12题)

    代码宏定义以及框架约定 #include <bits/stdc++.h> using namespace std; #define IOS ios_base::sync_with_stdi ...

  10. 【YashanDB知识库】YAC修改参数后关闭数据库夯住

    [问题分类]功能使用 [关键字]YAC,参数,SHM_POOL_SIZE,重启 [问题描述]YashanDB共享集群修改数据库配置参数,重启数据库时,数据库无法关闭. [问题原因分析]YAC的SHM_ ...