依赖注入 python_config-injector-简单的python依赖注入框架,便于应用程序的逻辑配置。-DustinMoriarty Installation Getting Started...

config-injector是一个简单的Python框架,用于定义可配置的函数并实现在运行时将配置数据注入这些函数。通过使用@config装饰器标记可调用对象,将参数分解为基本类型:字符串、整数、浮点数或字典。本文档介绍了如何安装、开始使用config-injector,并给出了示例代码。
摘要由CSDN通过智能技术生成

作者:DustinMoriarty

作者邮箱:dustin.moriarty@protonmail.com

首页:https://github.com/DustinMoriarty/config-injector

文档:None

下载链接

config-injector

Config-injector is a very simple framework which aims to do only two things: (1) define configurable functions and (2) inject configuration data into those functions at runtime.

Installation

Install with pip.

pip install config-injector

Getting Started

Annotate any callable as a configurable function using @config. Note that the @config decorator requires that you provide callable functions for each argument. These callable functions should return the expected type. The object is to break all arguments down to fundamental types: string, integer, float or dictionary.

from collections import namedtuple

from typing import Text, Dict, SupportsInt

from pathlib import Path

from config_injector import config, Injector

MockThing0 = namedtuple("MockThing0", ["arg_1", "arg_2", "arg_3", "arg_4"])

@config(arg_1=str, arg_2=str, arg_3=str, arg_4=str)

def mock_thing_0(arg_1: Text, arg_2: Text, arg_3: Text, arg_4: Text):

return MockThing0(arg_1, arg_2, arg_3, arg_4)

@config(arg_5=int, arg_6=int, arg_7=int, arg_8=int)

def mock_thing_1(arg_5, arg_6, arg_7, arg_8):

return {"key_a": arg_5, "key_b": arg_6, "key_c": arg_7, "key_d": arg_8}

@config(t0=mock_thing_0, t1=mock_thing_1, arg_9=str)

def mock_things(t0: MockThing0, t1: Dict[SupportsInt], arg_9: Text):

return (t0, t1, arg_9)

def get_things(config_file=Path("config.json")):

injector = Injector()

injector.load_file(config_file)

return injector["things"].instantiate(mock_things)

Now that the configurable functions are annotated, we can write a configuration for them.

{

"things": {

"t0": {"arg_1": "a", "arg_2": "b", "arg_3": "c", "arg_4": "d"},

"t1": {"arg_5": 1, "arg_6": 2, "arg_7": 3, "arg_8": 4},

"arg_9": "e"

}

}

This configuration file can be loaded in the runtime portion of our implementation using get_things() to instantiate the configured objects created by our functions.

Copy from pypi.org

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值