asyncio-loop-local 存储空间,单例和延迟 __aexit__'s。初始化该池一次并重用它!
项目描述
asyncio-loop-local
asyncio-loop-local 存储空间,单例和延迟 aexit's。初始化该池一次并重用它!
为什么需要有循环本地事物
假设您有一些异步上下文管理器,如 aiohttp.ClientSession
async with aiohttp.ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(await resp.text())
但是文档告诉您:“不要为每个请求创建一个会话”。因此,您需要以某种方式重用它,这意味着您需要在某处初始化它,然后传递给可能需要它的所有代码,或者……使用全局变量?一定有更好的方法。
sticky_singleton_acm
这是解决这个问题的全能解决方案
_ClientSession = asyncio_loop_local.sticky_singleton_acm(ClientSession)
...
async _ClientSession() as session:
async with session.get('http://httpbin.org/get') as resp:
print(await resp.text())
包装器为您提供了
- 相同的
ClientSession
,对于传递给它每个参数的组合(单例) - 当块结束时不会
__aexit__
,只有当异步事件循环关闭时才会(粘性 ACM)
enter_once
+ singleton
那些想节省一层缩进(毕竟,缩进消除是一个空操作,因为 __aexit__
的影响已经被延迟)的人可能会对组合两个更简单的原语达到相同的效果感兴趣
_ClientSession = asyncio_loop_local.singleton(ClientSession)
...
session = await asyncio_loop_local.enter_once(_ClientSession())
async with session.get('http://httpbin.org/get') as resp:
print(await resp.text())
singleton
装饰生成某个东西的可调用对象,返回的值将被缓存在每个异步循环中(以及每个传递的参数)。
_ClientSession = asyncio_loop_local.singleton(ClientSession)
_ClientSession() is _ClientSession() # as long you're in the same event loop
enter_once
现在调用异步上下文管理器的 __anter__
,将 __aexit__
延迟到事件循环的末尾。对同一对象的重复 enter_once
尝试将不会执行任何操作。
session = await asyncio_loop_local.enter_once(ClientSession())
...
# __aexit__ will be executed at the end of the event loop
sticky_acm
包装异步上下文管理器。《code>__anter__仅代理原始上下文管理器的__aenter__
,__aexit__
不执行任何操作,并延迟到事件循环的末尾。它类似于enter_once
,但以适用于async with
的形式。
cs = asyncio_loop_local.sticky_acm(ClientSession())
async with cs: # __aenter__'s
...
# __aexit__ will be executed at the end of the event loop
进入
现在调用异步上下文管理器的__anter__
,将__aexit__
延迟到事件循环的末尾。
session = await asyncio_loop_local.enter_once(ClientSession())
...
# __aexit__ will be executed at the end of the event loop
存储
异步循环局部存储。类似于线程局部,但循环局部。上述所有技巧都是基于它的。
alls = asyncio_loop_local._storage.storage() # gives a loop-associated dict
alls['purpose'] = ('whatever', {'you': 'want'})
如果您想使用锁定,请考虑以下内容
class LockingDict(asyncio.Lock, dict): pass
alls['careful'] = LockingDict()
with alls['careful'] as d:
d['a'] = 'b'
_atexit
还有一个异步循环局部atexit钩子实现。目前它是私有的,直到有人表现出兴趣。
项目详情
关闭
asyncio_loop_local-0.0.4.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | d4cde7234066a1adc3c27c6dd6a8dc2d87173de3702f9ae0948e44b8a46edde6 |
|
MD5 | bbc612dbf9a67f274fff64b53f96780c |
|
BLAKE2b-256 | 842c6b55ad2e0356598f35f296533b7f1e14426403c8a41525b438b0d96110f2 |
关闭
asyncio_loop_local-0.0.4-py3-none-any.whl的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | b3fc14b40349190b3488ed62a0e2f3647c79c3b5ab6b652bcb3a2e139d2192e2 |
|
MD5 | 583149bbdde12a7de1c49ce2f865cbb8 |
|
BLAKE2b-256 | 7405a59804e2e68ae1316e3d577738d1cc045936e9a5d03f3e42a9c0c9485625 |