python - 使用 Asyncio 执行 HTTP 请求
问题描述
以下函数需要异步发送请求:
devices.csv 中的行数 = 100 万
必需:每天为所有 100 万行发送 POST 请求,持续 3 天
def check_in():
logging.info('Starting')
day = 0
while day < 3:
logging.info('Check-in Day = ' + str(day))
with open('devices.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
device_sn = row['serial_number']
payload = {
"product": "##",
"board": "###",
"hardware_id": "0000",
"usage_id": "000",
"mac_address": row['mac_address'],
"serial_number": row['serial_number']
}
logging.info(
'Check-in device: ' + device_sn)
checkin_post(payload, device_sn)
day += 1
def checkin_post(payload, device_sn):
payload = payload
serial_number = device_sn
print('\n' + 72 * '=' + '\nPOST /device/' +
serial_number + '/check-in')
resp = requests.post(base_url + '/device/' +
serial_number + '/check-in', auth=auth, json=payload)
print(resp.status_code)
代码可能会更改为可能类似于:
async def checkin_post(payload, device_sn):
payload = payload
serial_number = device_sn
print('\n' + 72 * '=' + '\nPOST /device/' +
serial_number + '/check-in')
resp = requests.post(base_url + '/device/' +
serial_number + '/check-in', auth=auth, json=payload)
return resp.status_code
async def main(payload, device_sn):
checkin_post(payload, device_sn)
此外,由于没有await
,它并不是真正的异步。
解决方案
如果您现在已经解决了,很抱歉回复晚了。但是您需要返回 ensure_future 对象。你可以试试下面的代码:
async def check_in():
logging.info('Starting')
count = 0
futures = []
while count < 3:
logging.info('Check-in Day = ' + str(count))
with open('devices.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
device_sn = row['serial_number']
payload = {
"product": "##",
"board": "###",
"hardware_id": "0000",
"usage_id": "000",
"mac_address": row['mac_address'],
"serial_number": row['serial_number']
}
logging.info(
'Check-in device: ' + device_sn)
async with aiohttp.ClientSession() as session:
async with session.post(base_url + '/device/' + device_sn + '/check-in', auth=auth, json=payload) as resp:
futures.append(asyncio.ensure_future(await resp.status))
count += 1
return await asyncio.gather(*futures)
def main():
loop = asyncio.get_event_loop()
futures = asyncio.ensure_future(check_in())
responses = loop.run_until_complete(futures)
推荐阅读
- c - 确认消息已使用 socketCAN 发送到 CAN 总线
- r - 添加第二个 y 轴作为第一个 x 和 y 轴的公式
- reactjs - 从映射中排除项目
- c++ - sort() 方法 c++ 中的比较器函数。为大量数字获得不同的解决方案
- angular - Angular 8 - 将所有材料模块导入主应用程序模块是否比在不同模块中导入单个材料模块更好?
- android - Samsung Health SDK - Android : 读取理想时间的总燃烧卡路里
- docker - 如何在运行时将敏感数据发送到 docker 容器
- linux - 如何删除基于另一个文件的行?
- flutter - 如何在flutter中创建自定义tabBar
- c++ - 无法 typedef std::chrono::microseconds 覆盖其定义以更改其基础类型