为什么要对aiohttp使用显式循环参数? [英] Why use explicit loop parameter with aiohttp?

查看:135
本文介绍了为什么要对aiohttp使用显式循环参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

aiohttp 库的文档指出:


循环–用于处理HTTP请求的事件循环。如果param为None,则asyncio.get_event_loop()用于获取默认事件循环,但我们强烈建议在所有地方使用显式循环。 (可选)

loop – event loop used for processing HTTP requests. If param is None, asyncio.get_event_loop() is used for getting default event loop, but we strongly recommend to use explicit loops everywhere. (optional)

可以将循环传递给 ClientSession 对象,以提供模块级功能等。

It is possible to pass the loop to ClientSession objects, to provided "module-level" functions etc.

我是整个异步编程概念的新手,您能否向我解释为什么建议显式提供要使用的循环,而不是让对象/函数仅使用默认值?

I am new to the asynchronous programming concept as a whole, could you explain to me why it's recommended to explicitely provide the loop to use, rather than letting the objects/functions just use the default?

我想到的一种用途是通过能够提供我自己的循环模拟使测试变得更容易,是否存在性能原因?

One use that comes to mind is making testing easier, by being able to provide my own loop mocks, is there a performance reason?

推荐答案

原因是可读性,而不是性能。

The reason is readability and not performance.

显式指定循环将使开发人员更容易查看循环实例的来源,并可能使其更容易

Specifying a loop explicitly will make it easier for a developer to see where the loop instance originates from, and might make it easier to change the loop if a custom loop needs to be injected to the program.

另一个流行的选择是从不指定循环参数,因此,阿苏我总是调用 asyncio.get_event_loop()来获取循环实例。

Another popular option would be to never specify the loop parameter, and therefore assume asyncio.get_event_loop() is always called to get a loop instance.

(可以使用更多多于一个循环-例如在不同的线程中,但这不是常见的用例)

(It is possible to use more than one loop - for example in different threads, but this is not a common use case)

这篇关于为什么要对aiohttp使用显式循环参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆