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. 《Python数据可视化之matplotlib实践》 源码 第一篇 入门 第四章

    图 4.1 import matplotlib import matplotlib.pyplot as plt import numpy as np # 设置matplotlib正常显示中文和负号 m ...

  2. 华为高性能计算(HPC)文档——技术支持>智能计算解决方案>高性能计算>HPC

    链接地址: https://support.huawei.com/enterprise/zh/server-solutions/hpc-pid-253585671 ================== ...

  3. 首次尝试SeaTunnel同步Doris至Hive?这些坑你不能不避

    笔者使用SeaTunnel 2.3.2版本将Doris数据同步到Hive(cdh-6.3.2)首次运行时有如下报错,并附上报错的解决方案: java.lang.NoClassDefFoundError ...

  4. Quartz.NET 的使用

    先貼使用代碼: 1 using Quartz; 2 using Quartz.Impl; 3 using Quartz.Logging; 4 using System; 5 using System. ...

  5. 组长:你熟悉过React,开发个Next项目模板吧,我:怎么扯上关系的?

    组长:你熟悉过React,开发个Next项目模板吧,我:怎么扯上关系的? 最近工作安排我开发一个Next.js项目模板,心里默笑,React用得少得都快忘光了,现在得搞Next?虽然我曾是React的 ...

  6. MarginNote 4 内存泄露?

    在床上用电脑的时候突然发现电脑风扇呼呼响,一摸很烫,以为是被子把出风口堵住了,于是调整角度继续用.结果一段时间之后风扇还是狂转不停,然后收到了这样的提示.不看不知道一看吓一跳,MarginNote 4 ...

  7. Ubuntu 设置中文

    首先安装中文语言包: sudo apt install -y language-pack-zh-hans 接下来在 ~/.zshrc 或 ~/.bashrc 中添加如下内容: export \ LAN ...

  8. 【图文教程】Centos单机安装Redis

    1.1.安装Redis依赖 Redis是基于C语言编写的,因此首先需要安装Redis所需要的gcc依赖: yum install -y gcc tcl 1.2.上传安装包并解压 ​ 例如,凯哥将其放到 ...

  9. MySQL Installer 方式安装MySQL

    一.下载MySQL 首先,去数据库的官网https://dev.mysql.com/downloads/windows/installer/8.0.html下载MySQL. 点击download进入下 ...

  10. 2024 秋季PAT认证甲级(题解A1-A4)

    2024 秋季PAT认证甲级(题解A-D) 写在前面 这一次PAT甲级应该是最近几次最简单的一次了,3个小时的比赛差不多30分钟就ak了(也是拿下了整场比赛的rk1),下面是题解报告,每个题目差不多都 ...