【问题标题】:Using multithreading for api requests in python在 python 中使用多线程处理 api 请求
【发布时间】:2021-06-28 04:02:29
【问题描述】:

对于我的项目,我需要请求一个 api 并将结果存储在一个列表中。但是没有。我需要提供超过 5000 个不同正文值的请求。因此,需要花费大量时间才能完成。有什么方法可以并行发送请求以快速完成该过程。我尝试了一些线程代码,但我无法找出解决这个问题的方法。

import requests
res_list=[]
l=[19821, 29674 , 41983, 40234 ,.....] # Nearly 5000 items for now  and the count may increase in future
for i in l:
    URL ="https://api.something.com/?key=xxx-xxx-xxx&job_id={0}".format(i)
    res = requests.get(url=URL)
    res_list.append(res.text)

【问题讨论】:

  • 你的问题是?到目前为止,它只是一个声明:“我无法编程我需要的东西”。

标签: python multithreading api python-multiprocessing python-multithreading


【解决方案1】:

您可能只需要异步进行查询。类似的东西:

import asyncio

import aiohttp

NUMBERS = [1, 2, 3]


async def call():
    async with aiohttp.ClientSession() as session:
        for num in NUMBERS:
            async with session.get(f'http://httpbin.org/get?{num}') as resp:
                print(resp.status)
                print(await resp.text())


if __name__ == '__main__':
    loop = asyncio.new_event_loop()
    loop.run_until_complete(call())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多