如何在python中异步运行http请求

如何在python中异步运行http请求,python,asynchronous,python-requests,python-asyncio,Python,Asynchronous,Python Requests,Python Asyncio,这段代码是我同步运行的 import requests URL = "http://maps.googleapis.com/maps/api/geocode/json" location = "delhi technological university" PARAMS = {'address':location} for _ in range(1,100): r = requests.get(url = URL, p

这段代码是我同步运行的

import requests 
  
URL = "http://maps.googleapis.com/maps/api/geocode/json"
  
location = "delhi technological university"
  
PARAMS = {'address':location} 
  

for _ in range(1,100):
    r = requests.get(url = URL, params = PARAMS) 
    print(r)

如何使用python异步运行相同的代码

我试过这个:

import requests
import asyncio

loop = asyncio.get_event_loop()

URL = "http://maps.googleapis.com/maps/api/geocode/json"
  
location = "delhi technological university"
  
PARAMS = {'address':location} 


async def run():
    for j in range(1,100):
        
        r = requests.get(url = URL, params = PARAMS)
        
if __name__ == "__main__":
    loop.run_until_complete(run())
    loop.close()
 



尝试了上述代码,但出现运行时错误。RuntimeError:此事件循环已在运行

您如何运行这些代码?有些环境已经运行了一个循环,这将导致该错误。然而,一旦您解决了这个问题,您的代码仍然不会真正是异步的。第一个问题是请求不支持异步IO。您需要使用不同的库,如aiohttp。然后需要重构代码,因为在循环中等待会阻止迭代,直到调用返回。您需要使用类似于
asyncio.gather
的方法来允许同时进行其他调用。您可以共享任何文档吗