跳转到主要内容

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 (47.1 kB 查看哈希值)

上传时间

构建分布

asyncio_loop_local-0.0.4-py3-none-any.whl (33.0 kB 查看哈希值)

上传时间 Python 3

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面