Python的简单异步依赖注入器
项目描述
# ainject Python的简单异步依赖注入器。
## 原因 * 没有支持 async/await 的异步DI。 * 简化事物。
## 特性 * 异步实例工厂。 * 支持异步 __init__ 和 __new__。 * 简单的API。
## 要求 * Python 3.5+ * setuptools >= 30.3.0 (仅安装)
## 使用只需 bind 一些工厂与一些名称,并在您想要的位置 inject/instance 它们。 ` python >>> import ainject ` ### 绑定和实例化 简单绑定带名称: ` python >>> async def async_factory(): ... return "async_value" ... >>> def sync_factory(): ... return "sync_value" >>> ainject.bind(async_factory, name="async") >>> await ainject.instance("async") 'async_value' >>> ainject.bind(sync_factory, name="sync") >>> await ainject.instance("sync") 'sync_value' >>> ` 正如您所看到的,您应该始终 await 您的结果,即使工厂实际上是同步的。
不带名称的绑定: ` python >>> ainject.bind(async_factory) >>> await ainject.instance(async_factory) 'async_value' >>> ainject.bind(sync_factory) >>> await ainject.instance(sync_factory) 'sync_value' >>> ` 在这种情况下,name 是 factory 本身。这相当于: ` python >>> ainject.bind(async_factory, name=async_factory) >>> ` 因此,您可以使用任何可哈希的值作为名称,甚至可以省略它来自动命名。
默认情况下,绑定以“单例”模式进行。这意味着,第一次访问实例时,它将被缓存,对于后续的每个实例请求,将使用缓存的版本: `python >>> def factory(): ... return [] ... >>> ainject.bind(factory) >>> a = await ainject.instance(factory) >>> b = await ainject.instance(factory) >>> a, b ([], []) >>> a is b True >>> ` 对于非单例使用,将 singleton=False 传递给绑定方法。在这种情况下,每次实例化实际上都会执行工厂函数: `python >>> def factory(): ... return [] ... >>> ainject.bind(factory, singleton=False) >>> a = await ainject.instance(factory) >>> b = await ainject.instance(factory) >>> a, b ([], []) >>> a is b False >>> `
### 注入 注入是通过 inject 装饰器完成的: `python >>> @ainject.inject(x=factory) ... def foo(x): ... print(x) ... ... >>> await foo() [] >>> ` 请记住,在装饰器之前应定义“名称”,或者只需使用字符串作为名称。另外,请注意,所有使用 inject 装饰器包装的内容都变为可等待的: `python >>> @ainject.inject(x="async") ... class A: ... def __init__(self, x): ... self.x = x ... ... ... >>> a = await A() >>> ` 即使是类实例化。这种“魔法”的副作用是您可以使用 async __init__ 和 async __new__: `python >>> @ainject.inject() ... class A: ... async def __new__(self, x): ... ... ... return super().__new__(self) ... async def __init__(self, x): ... self.x = x ... ... ... >>> a = await A(3)` 如您所见,您甚至可以注入空值。
项目详细信息
下载文件
下载您平台的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。
源代码分发
构建分发
ainject-0.0.3.tar.gz 的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | bb58cb7162169f10b7bcf94440b4a21eab74870f4dcc4cee4fe676020cc7b839 |
|
MD5 | 10387e8fd5b74ea8608386e7bd141ea6 |
|
BLAKE2b-256 | d0654ea710556dc9e44c4734c97795706eeddc3997781395b5317a38aefe8fe4 |