[英]Do I need to keep track of the asyncio event loop, or can I just call asyncio.get_event_loop when it is needed?
I am writing a REST API using aiohttp
.我正在使用
aiohttp
编写 REST API。
Some of the coroutines need to call the database using the aiomysql
library .一些协程需要使用
aiomysql
库调用数据库。 The documentation for aiomysql
has the following example: aiomysql
的文档有以下示例:
import asyncio
import aiomysql
loop = asyncio.get_event_loop()
async def test_example():
conn = await aiomysql.connect(host='127.0.0.1', port=3306,
user='root', password='', db='mysql',
loop=loop)
cur = await conn.cursor()
await cur.execute("SELECT Host,User FROM user")
print(cur.description)
r = await cur.fetchall()
print(r)
await cur.close()
conn.close()
loop.run_until_complete(test_example())
My question is concerning the definition of the global variable loop
:我的问题是关于全局变量
loop
的定义:
loop = asyncio.get_event_loop()
Do I really need to keep loop
as a global variable somewhere, or can I just call asyncio.get_event_loop()
when I need it?我是否真的需要将
loop
作为全局变量保留在某处,或者我可以在需要时调用asyncio.get_event_loop()
吗?
For example, it the code example above, I could get the event loop when I am connecting to the database:例如,上面的代码示例,当我连接到数据库时,我可以获得事件循环:
conn = await aiomysql.connect(host='127.0.0.1', port=3306,
user='root', password='', db='mysql',
loop=asyncio.get_event_loop())
Is there a non-trivial runtime cost to calling asyncio.get_event_loop()
or something else that I am missing?调用
asyncio.get_event_loop()
或我缺少的其他东西是否有重要的运行时成本?
loop
argument should go. loop
参数应该去。
aiomysql should be updated to don't accept the loop. aiomysql 应该更新为不接受循环。
You can just skip loop=...
in your code right now because aiomysql.connect()
has the default loop=None
value for the argument.您现在可以在代码中跳过
loop=...
,因为aiomysql.connect()
具有参数的默认loop=None
值。
In general, asyncio.get_event_loop()
will be deprecated;一般来说,
asyncio.get_event_loop()
将被弃用; asyncio.get_running_loop()
is recommended for the usage from an async code when needed. asyncio.get_running_loop()
建议在需要时从异步代码中使用。 Passing an explicit loop to asyncio API is deprecated starting from Python 3.8.从 Python 3.8 开始,不推荐将显式循环传递给 asyncio API。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.