【问题标题】:Executing HTTP requests using Asyncio使用 Asyncio 执行 HTTP 请求
【发布时间】:2019-10-14 21:27:30
【问题描述】:

以下函数需要异步发送请求:

没有。 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,它并不是真正的异步。

【问题讨论】:

  • 就目前而言,这个问题太宽泛了。您是否尝试过自己将其从请求转换为异步?
  • @wpercy 我已经发布了我尝试过的内容,我确定它不正确。
  • 要么在线程池中执行对请求的调用,要么查看 aiohttp

标签: python python-3.x python-requests python-asyncio


【解决方案1】:

如果您现在已经解决了问题,那么抱歉回复晚了。 但是您需要返回 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)

【讨论】:

  • 我已经更新了我的问题,payloadserial_number 是从另一个函数传递过来的。
  • 你试过删除 print(resp.status) 语句吗?也许您可以在等待响应之前打印状态。
  • 请在下面的答案中查看我的试验。这也不行。
  • 请编辑您的原始问题而不是发布新答案:stackoverflow.com/help/editing
  • @jtbandes 感谢您的审阅。编辑了我原来的答案。
猜你喜欢
  • 2018-04-28
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
相关资源
最近更新 更多