我很难理解为什么我得到"RuntimeError:此事件循环已经在运行"运行时错误.我试图从" https://aiohttp.readthedocs.io/en/stable/ " 运行代码片段但是,我一直遇到同样的问题.
教程中的代码片段:
import aiohttp
import asyncio
import async_timeout
async def fetch(session, url):
async with async_timeout.timeout(10):
async with session.get(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
html = await fetch(session, 'http://python.org')
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Run Code Online (Sandbox Code Playgroud)
教程片段的结果(从spyder IDE运行代码时):
RuntimeError:此事件循环已在运行
<!doctype html>"
Run Code Online (Sandbox Code Playgroud)
...(更多HTML)
个人代码段(不是上面引用的教程):
import aiohttp
import asyncio
import time
urls = ['https://api.robinhood.com/quotes/c4f6720a-0364-4e7b-8c41-705696759e1a/']
async def fetch(client, url):
async with client.request('get', url) as response:
if response.status == 200:
data = await response.text()
else:
data …Run Code Online (Sandbox Code Playgroud) 我正在尝试解决此错误:RuntimeError: Cannot close a running event loop在我的异步过程中。我相信这是因为在任务仍未完成时发生故障,然后我尝试关闭事件循环。我以为我需要在关闭事件循环之前等待其余的响应,但是我不确定如何在我的特定情况下正确完成该操作。
def start_job(self):
if self.auth_expire_timestamp < get_timestamp():
api_obj = api_handler.Api('Api Name', self.dbObj)
self.api_auth_resp = api_obj.get_auth_response()
self.api_attr = api_obj.get_attributes()
try:
self.queue_manager(self.do_stuff(json_data))
except aiohttp.ServerDisconnectedError as e:
logging.info("Reconnecting...")
api_obj = api_handler.Api('API Name', self.dbObj)
self.api_auth_resp = api_obj.get_auth_response()
self.api_attr = api_obj.get_attributes()
self.run_eligibility()
async def do_stuff(self, data):
tasks = []
async with aiohttp.ClientSession() as session:
for row in data:
task = asyncio.ensure_future(self.async_post('url', session, row))
tasks.append(task)
result = await asyncio.gather(*tasks)
self.load_results(result)
def queue_manager(self, method):
self.loop = asyncio.get_event_loop()
future = …Run Code Online (Sandbox Code Playgroud)