事件循环已运行时在Python类中等待协程的asyncio问题
关于asyncio + aiohttp异步请求Bittrex API的问题分析
从你贴的代码片段来看,你应该是在尝试用asyncio和aiohttp异步获取Bittrex的交易市场行情数据对吧?不过代码在async with aiohttp.C...这里截断了,先给你补全完整的可运行代码,并梳理常见的坑和解决方案:
补全后的完整可运行示例
import asyncio import aiohttp import async_timeout import json async def fetch(session, url): async with async_timeout.timeout(10): async with session.get(url) as response: # 先检查响应状态码,避免解析无效内容 response.raise_for_status() return await response.text() async def get_bittrex_marketsummary(session, currency_pair): url = f'https://bittrex.com/api/v1.1/public/getmarketsummary?market={currency_pair}' try: response_text = await fetch(session, url) return json.loads(response_text) except Exception as e: print(f"请求{currency_pair}失败: {str(e)}") return None async def main(): # 推荐复用ClientSession,它会自动管理连接池,提升性能 async with aiohttp.ClientSession() as session: # 单个交易对请求示例 summary = await get_bittrex_marketsummary(session, 'btc-usdt') if summary: print(f"BTC-USDT行情数据:\n{summary}") # 多个交易对并发请求示例 print("\n--- 批量请求多个交易对 ---") currency_pairs = ['eth-btc', 'ltc-btc', 'bnb-btc'] tasks = [get_bittrex_marketsummary(session, pair) for pair in currency_pairs] results = await asyncio.gather(*tasks) for pair, result in zip(currency_pairs, results): print(f"{pair}: {result}") if __name__ == '__main__': # Python 3.7+推荐用asyncio.run()启动异步任务 asyncio.run(main())
常见问题及解决方案
- 忘记加
await调用异步函数:如果直接调用get_bittrex_marketsummary(...)而不是await get_bittrex_marketsummary(...),只会得到一个协程对象,不会实际执行请求。 - 未正确管理
ClientSession:不要在每个请求里重复创建ClientSession,这会导致连接泄漏和性能下降,推荐用async with上下文管理器复用session。 - 并发请求被限流:如果批量请求过多,容易触发API限流,可通过
asyncio.Semaphore控制并发数:async def get_bittrex_marketsummary(session, currency_pair, semaphore): async with semaphore: # 原请求逻辑... async def main(): semaphore = asyncio.Semaphore(5) # 限制同时5个请求 tasks = [get_bittrex_marketsummary(session, pair, semaphore) for pair in currency_pairs] # ... - 未处理异常:网络请求可能遇到超时、连接错误、JSON解析失败等问题,一定要加上异常捕获,避免程序直接崩溃。
如果你有具体的报错信息(比如超时、返回空数据、任务阻塞等),或者实际需求和上面的示例不符,可以把完整的代码和问题细节补充清楚,我再帮你精准排查。
内容的提问来源于stack exchange,提问作者elmcrest
相关产品推荐
相关产品推荐

