{"id":20613881,"url":"https://github.com/python-tools/schema_entry","last_synced_at":"2026-01-21T13:33:46.241Z","repository":{"id":57464308,"uuid":"294850132","full_name":"Python-Tools/schema_entry","owner":"Python-Tools","description":"程序的入口树基类","archived":false,"fork":false,"pushed_at":"2024-06-19T06:51:11.000Z","size":6793,"stargazers_count":0,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-04-15T01:49:37.153Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Python-Tools.png","metadata":{"files":{"readme":"README.md","changelog":"Changelog.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-09-12T01:58:49.000Z","updated_at":"2024-06-19T06:49:29.000Z","dependencies_parsed_at":"2025-02-16T12:26:19.887Z","dependency_job_id":"d347cf7d-fd12-47ad-953c-153ddeb5a120","html_url":"https://github.com/Python-Tools/schema_entry","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Tools%2Fschema_entry","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Tools%2Fschema_entry/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Tools%2Fschema_entry/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Tools%2Fschema_entry/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Python-Tools","download_url":"https://codeload.github.com/Python-Tools/schema_entry/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248991540,"owners_count":21194894,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-16T11:11:19.300Z","updated_at":"2026-01-21T13:33:46.235Z","avatar_url":"https://github.com/Python-Tools.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 简介\n\n程序入口的构造工具.\n\n这个基类的设计目的是为了配置化入口的定义.通过继承和覆盖基类中的特定字段和方法来实现入口的参数配置读取.\n\n目前的实现可以依次从指定路径下的json文件,环境变量,命令行参数读取需要的数据.\n然后校验是否符合设定的json schema规定的模式,在符合模式后执行注册进去的回调函数.\n\n入口树中可以有中间节点,用于分解复杂命令行参数,中间节点不会执行.\n他们将参数传递给下一级节点,直到尾部可以执行为止.\n\n# 特性\n\n+ 根据子类的名字小写构造命令\n+ 根据子类的docstring,`epilog字段`和`description字段`自动构造,命令行说明.\n+ 根据子类的`schema字段`和`env_prefix字段`自动构造环境变量的读取规则.\n+ 根据子类的`default_config_file_paths字段`自动按顺序读取json,yaml格式配置文件中的参数.\n+ 根据`schema字段`构造命令行参数和配置校验\n+ 使用装饰器`@as_main`注册获取到配置后执行的函数\n+ 通过覆写`parse_commandline_args`方法来定义命令行参数的读取\n+ 入口节点可以通过方法`regist_sub`注册子节点\n\n# 安装\n\n```bash\npip install schema_entry\n```\n\n# 使用介绍\n\n## 动机\n\n`schema_entry`模块提供了一个基类`EntryPoint`用于构造复杂的程序入口.通常我们的程序入口参数有3个途径:\n\n1. 配置文件\n2. 环境变量\n3. 命令行参数\n\n在docker广泛应用之前可能用的最多的是命令行参数.但在docker大行其道的现在,配置文件(docker config)和环境变量(environment字段)变得更加重要.\n\n随之而来的是参数的校验问题,python标准库`argparse`本身有不错的参数约束能力,但配置文件中的和环境变量中的参数就需要额外校验了.\n\n这个项目的目的是简化定义入口这个非常通用的业务,将代码尽量配置化.\n\n## 使用方法\n\n首先我们来分析下一个入口形式.\n\n通常一个程序的入口可能简单也可能复杂,但无非两种\n\n1. 中间节点,比如`docker stack`, 它本质上并不执行操作,它只是表示要执行的是关于子模块的操作.当单独执行这条命令时实际上它什么都没做,它下面的子命令`git submodule add`这类才是实际可以执行的节点.而我定义这种中间节点单独被执行应该打印其帮助说明文本.\n2. 执行节点,比如`docker run`,这种就是`可以执行的节点`.\n\n本模块的基本用法是:\n\n1. 通过继承`EntryPoint`类并覆写其中的字段来定义不同的节点\n\n2. 通过实例化`EntryPoint`的子类并使用其实例方法`regist_subcmd`或者`regist_sub`来定义不同节点的类型和节点的调用顺序\n\n3. 使用`可以执行节点`的实例方法`as_main`(装饰器)来指定不同节点的入口函数.\n\n4. 命令行中按`根节点`到`可以执行节点`的顺序输入构造命令,获取来自配置文件,环境变量,命令行参数中的参数,作为注册入口函数的参数调用入口函数.\n\n### 节点名\n\n我们可以定义`_name`字段为节点命名,如果没有那么节点名则为子类类名的全小写形式.\n\n### 节点的帮助信息\n\n我们可以定义`usage`来定义用法帮助字符串,如果没有定义则会自动构造,中间节点会是`root subcmd ... [subcmd]`;\n可执行节点会是`root subcmd ... entry [options]`\n\n### 执行节点\n\n上面说过执行节点的任务有3个:\n\n1. 从配置文件,环境变量,命令行参数获取配置参数\n2. [可选]校验配置参数是否符合要求\n3. [可选]将配置作为参数引用到程序中.\n\n#### 通过定义`schema字段进行参数校验`\n\n我们可以定义`schema字段`来激活校验功能\n\n```python\nclass Test_A(EntryPoint):\n    default_config_file_paths = [\n        \"/test_config.json\",\n        str(Path.home().joinpath(\".test_config.json\")),\n        \"./test_config.json\"\n    ]\n    schema = {\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n        \"type\": \"object\",\n        \"properties\": {\n            \"a\": {\n                \"type\": \"integer\"\n            }\n        },\n        \"required\": [\"a\"]\n    }\n```\n\n`EntryPoint`的子类会在解析获得参数后校验参数字典是否符合schema中定义的模式.\n\n当然schema字段也不能乱写,它的规则是json schema的一个子集:\n\n```json\n{\n    \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n    \"type\": \"object\",\n    \"properties\": {\n        \"properties\": {\n            \"type\": \"object\",\n            \"minProperties\": 1,\n            \"additionalProperties\": False,\n            \"patternProperties\": {\n                \"^\\\\w+$\": {\n                    \"oneOf\": [\n                        {\n                            \"type\": \"object\",\n                            \"additionalProperties\": False,\n                            \"required\": [\"type\"],\n                            \"properties\": {\n                                \"type\": {\n                                    \"type\": \"string\",\n                                    \"const\": \"boolean\"\n                                },\n                                \"default\": {\n                                    \"type\": \"boolean\",\n                                },\n                                \"const\": {\n                                    \"type\": \"string\"\n                                },\n                                \"description\": {\n                                    \"type\": \"string\"\n                                },\n                                \"$comment\": {\n                                    \"type\": \"string\"\n                                },\n                                \"title\": {\n                                    \"type\": \"string\",\n                                    \"pattern\": \"^[a-b]|[d-z]$\"\n                                }\n                            }\n                        },\n                        {\n                            \"type\": \"object\",\n                            \"additionalProperties\": false,\n                            \"required\": [\"type\"],\n                            \"properties\": {\n                                \"type\": {\n                                    \"type\": \"string\",\n                                    \"const\": \"string\"\n                                },\n                                \"default\": {\n                                    \"type\": \"string\",\n                                },\n                                \"const\": {\n                                    \"type\": \"string\"\n                                },\n                                \"enum\": {\n                                    \"type\": \"array\",\n                                    \"items\": {\n                                        \"type\": \"string\"\n                                    }\n                                },\n                                \"maxLength\": {\n                                    \"type\": \"integer\",\n                                    \"minimum\": 0\n                                },\n                                \"minLength\": {\n                                    \"type\": \"integer\",\n                                    \"minimum\": 0\n                                },\n                                \"pattern\": {\n                                    \"type\": \"string\"\n                                },\n                                \"format\": {\n                                    \"type\": \"string\"\n                                },\n                                \"description\": {\n                                    \"type\": \"string\"\n                                },\n                                \"$comment\": {\n                                    \"type\": \"string\"\n                                },\n                                \"title\": {\n                                    \"type\": \"string\",\n                                    \"pattern\": r\"^[a-b]|[d-z]$\"\n                                }\n                            }\n                        },\n                        {\n                            \"type\": \"object\",\n                            \"additionalProperties\": false,\n                            \"required\": [\"type\"],\n                            \"properties\": {\n                                \"type\": {\n                                    \"type\": \"string\",\n                                    \"const\": \"number\"\n                                },\n                                \"default\": {\n                                    \"type\": \"number\",\n                                },\n                                \"const\": {\n                                    \"type\": \"number\"\n                                },\n                                \"enum\": {\n                                    \"type\": \"array\",\n                                    \"items\": {\n                                        \"type\": \"number\"\n                                    }\n                                },\n                                \"maximum\": {\n                                    \"type\": \"number\",\n                                },\n                                \"exclusiveMaximum\": {\n                                    \"type\": \"number\",\n                                },\n                                \"minimum\": {\n                                    \"type\": \"number\",\n\n                                },\n                                \"exclusiveMinimum\": {\n                                    \"type\": \"number\",\n\n                                },\n                                \"description\": {\n                                    \"type\": \"string\"\n                                },\n                                \"$comment\": {\n                                    \"type\": \"string\"\n                                },\n                                \"title\": {\n                                    \"type\": \"string\",\n                                    \"pattern\": \"^[a-b]|[d-z]$\"\n                                }\n                            }\n                        },\n                        {\n                            \"type\": \"object\",\n                            \"additionalProperties\": false,\n                            \"required\": [\"type\"],\n                            \"properties\": {\n                                \"type\": {\n                                    \"type\": \"string\",\n                                    \"const\": \"integer\"\n                                },\n                                \"default\": {\n                                    \"type\": \"integer\",\n                                },\n                                \"const\": {\n                                    \"type\": \"integer\"\n                                },\n                                \"enum\": {\n                                    \"type\": \"array\",\n                                    \"items\": {\n                                        \"type\": \"integer\"\n                                    }\n                                },\n                                \"maximum\": {\n                                    \"type\": \"integer\",\n                                },\n                                \"exclusiveMaximum\": {\n                                    \"type\": \"integer\",\n                                },\n                                \"minimum\": {\n                                    \"type\": \"integer\",\n\n                                },\n                                \"exclusiveMinimum\": {\n                                    \"type\": \"integer\",\n\n                                },\n                                \"description\": {\n                                    \"type\": \"string\"\n                                },\n                                \"$comment\": {\n                                    \"type\": \"string\"\n                                },\n                                \"title\": {\n                                    \"type\": \"string\",\n                                    \"pattern\": \"^[a-b]|[d-z]$\"\n                                }\n                            }\n                        },\n                        {\n                            \"type\": \"object\",\n                            \"additionalProperties\": false,\n                            \"required\": [\"type\"],\n                            \"properties\": {\n                                \"type\": {\n                                    \"type\": \"string\",\n                                    \"const\": \"array\"\n                                },\n                                \"default\": {\n                                    \"type\": \"array\",\n                                    \"items\": {\n                                        \"type\": [\"string\", \"number\", \"integer\"]\n                                    }\n                                },\n                                \"items\": {\n                                    \"type\": \"object\",\n                                    \"required\": [\"type\"],\n                                    \"additionalProperties\": false,\n                                    \"properties\": {\n                                        \"type\": {\n                                            \"type\": \"string\",\n                                            \"enum\": [\"string\", \"number\", \"integer\"]\n                                        },\n                                        \"enum\":{\n                                            \"type\": \"array\"\n                                        }\n                                    }\n                                },\n                                \"description\": {\n                                    \"type\": \"string\"\n                                },\n                                \"$comment\": {\n                                    \"type\": \"string\"\n                                },\n                                \"title\": {\n                                    \"type\": \"string\",\n                                    \"pattern\": \"^[a-b]|[d-z]$\"\n                                }\n                            }\n                        }\n                    ]\n\n                }\n            }\n        },\n        \"type\": {\n            \"type\": \"string\",\n            \"const\": \"object\"\n        },\n        \"required\": {\n            \"type\": \"array\",\n            \"items\": {\n                \"type\": \"string\"\n            }\n        }\n\n    },\n    \"required\": [\"properties\", \"type\"]\n}\n```\n\n简而言之就是:\n\n1. 最外层必须有`properties`和`type`字段且`type`字段必须为`object`,可以有`required`字段\n2. 最外层`properties`中的字段名必须是由`数字`,`字母`和`_`组成,\n3. 字段类型只能是`string`,`boolean`,`number`,`integer`,`array`之一\n4. 字段类型如果为`array`则内部必须要有`items`且`items`中必须有`type`字段,且该`type`字段的值必须为`string`,`number`,`integer`之一\n\n\n如果我们不想校验,那么可以设置`verify_schema`为`False`强行关闭这个功能.\n\n#### 从定义的schema中获取默认配置\n\n我们在定义schema时可以在`\"properties\"`字段定义的模式描述中通过`default`字段指定描述字段的默认值\n\n```python\nclass Test_A(EntryPoint):\n    schema = {\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n        \"type\": \"object\",\n        \"properties\": {\n            \"a_a\": {\n                \"type\": \"number\"\n                \"default\": 10.1\n            }\n        },\n        \"required\": [\"a_a\"]\n    }\n```\n\n这样即便没有其他输入这个参数也会有这个默认值兜底\n\n#### 从指定配置文件中读取配置\n\n我们可以使用字段`default_config_file_paths`指定从固定的几个路径中读取配置文件,配置文件支持`json`和`yaml`两种格式.\n我们也可以通过字段`config_file_only_get_need`定义从配置文件中读取配置的行为(默认为`True`),\n 当置为`True`时我们只会在配置文件中读取schema中定义的字段,否则则会加载全部字段.\n\n也可以通过设置`load_all_config_file = True`来按设定顺序读取全部预设的配置文件位置\n\n默认配置文件地址是一个列表,会按顺序查找读取,只要找到了满足条件的配置文件就会读取.\n\n```python\nfrom pathlib import Path\nfrom schema_entry import EntryPoint\n\nclass Test_A(EntryPoint):\n\n    default_config_file_paths = [\n        \"/test_config.json\",\n        str(Path.home().joinpath(\".test_config.json\")),\n        \"./test_config.json\",\n        \"./test_config_other.json\"\n    ]\n```\n\n##### 指定特定命名的配置文件的解析方式\n\n可以使用`@regist_config_file_parser(config_file_name)`来注册如何解析特定命名的配置文件.这一特性可以更好的定制化配置文件的读取\n\n```python\nclass Test_AC(EntryPoint):\n    load_all_config_file = True\n    default_config_file_paths = [\n        \"./test_config.json\",\n        \"./test_config1.json\",\n        \"./test_other_config2.json\"\n    ]\nroot = Test_AC()\n\n@root.regist_config_file_parser(\"test_other_config2.json\")\ndef _1(p: Path) -\u003e Dict[str, Any]:\n    with open(p) as f:\n        temp = json.load(f)\n    return {k.lower(): v for k, v in temp.items()}\n\n```\n\n如果想在定义子类时固定好,也可以定义`_config_file_parser_map:Dict[str,Callable[[Path], Dict[str, Any]]]`\n\n```python\ndef test_other_config2_parser( p: Path) -\u003e Dict[str, Any]:\n    with open(p) as f:\n        temp = json.load(f)\n    return {k.lower(): v for k, v in temp.items()}\nclass Test_AC(EntryPoint):\n    load_all_config_file = True\n    default_config_file_paths = [\n        \"./test_config.json\",\n        \"./test_config1.json\",\n        \"./test_other_config2.json\"\n    ]\n    _config_file_parser_map = {\n        \"test_other_config2.json\": test_other_config2_parser\n    }\n\nroot = Test_AC()\n\n```\n\n#### 从环境变量中读取配置参数\n\n要从环境变量中读取配置必须设置`schema`字段,`EntryPoint`会按照其中`properties`字段定义的字段范围和字段类型解析环境变量.\n\n环境变量key的规则为`前缀_字段名的大写`.前缀的默认值为`...父节命令节点的父命令节点大写_父节命令节点大写_子命令节点大写`.\n我们也可以通过设定`env_prefix`字段来替换默认前缀,替换的前缀依然会被转化为大写.\n\n```python\nclass Test_A(EntryPoint):\n    env_prefix = \"app\"\n    schema = {\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n        \"type\": \"object\",\n        \"properties\": {\n            \"a_a\": {\n                \"type\": \"number\"\n            }\n        },\n        \"required\": [\"a_a\"]\n    }\n```\n\n如果我们不希望从环境变量中解析配置,那么也可以设置`parse_env`为`False`\n\n#### 从命令行参数中获取配置参数\n\n当我们定义好`schema`后所有schema中定义好的参数都可以以`--xxxx`的形式从命令行中读取,需要注意schema中定义的字段中`_`会被修改为`-`.\n如果定义的字段模式中含有`title`字段,则使用title字段作为命令行缩写即`-x`的形式\n\n这个命令行读取是使用的标准库`argparse`,构造出的解析器中`useage`,`epilog`和`description`会由类中定义的`usage`,`epilog`和docstring决定;`argv`则为传到节点处时剩下的命令行参数(每多一个节点就会从左侧摘掉一个命令行参数).\n\n通常情况下构造的命令行解析器全部都是可选项,如果我们希望指定`schema`中一项是没有`--`的那种配置,那么可以在定义类时指定`argparse_noflag`为想要的字段,如果希望命令行中校验必填项则可以在定义类时指定`argparse_check_required=True`.需要注意如果一个字段被指定为了`noflag`那么它就是必填项了.\n\n```python\nclass Test_A(EntryPoint):\n    argparse_noflag = \"a\"\n    argparse_check_required=True\n    schema = {\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n        \"type\": \"object\",\n        \"properties\": {\n            \"a\": {\n                \"type\": \"number\"\n            },\n            \"b\": {\n                \"type\": \"number\"\n            }\n        },\n        \"required\": [\"a\",\"b\"]\n    }\n```\n\n命令行中默认使用`-c`/`--config`来指定读取配置文件,它的读取行为受上面介绍的从自定义配置文件中读取配置的设置影响.\n\n#### 配置的读取顺序\n\n配置的读取顺序为`schema中定义的default值`-\u003e`配置指定的配置文件路径`-\u003e`命令行指定的配置文件`-\u003e`环境变量`-\u003e`命令行参数`,而覆盖顺序则是反过来.\n\n#### 注册入口的执行函数\n\n我们使用实例的装饰器方法`as_main`来实现对执行节点入口函数的注册,注册的入口函数会在解析好参数后执行,其参数就是解析好的`**config`\n\n```python\n\nroot = Test_A()\n@root.as_main\ndef main(a,b):\n    print(a)\n    print(b)\n\n```\n\n另一种指定入口函数的方法是重写子类的`do_main(self)-\u003eNone`方法\n\n```python\nclass Test_A(EntryPoint):\n    argparse_noflag = \"a\"\n    argparse_check_required=True\n    schema = {\n        \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n        \"type\": \"object\",\n        \"properties\": {\n            \"a\": {\n                \"type\": \"number\"\n            },\n            \"b\": {\n                \"type\": \"number\"\n            }\n        },\n        \"required\": [\"a\",\"b\"]\n    }\n    def do_main(self)-\u003eNone:\n        print(self.config)\n```\n\n#### 直接从节点对象中获取配置\n\n节点对象的`config`属性会在每次调用时copy一份当前的配置值,config是不可写的.\n\n```python\nprint(root.config)\n```\n\n### 中间节点\n\n中间节点并不能执行程序,它只是用于描述一个范围内的命令集合,因此它的作用就是充当`help`指令.我们定义中间节点并不能执行.但必须有至少一个子节点才是中间节点.因此即便一个节点定义了上面的配置,只要它有子节点就不会按上面的执行流程执行.\n\n利用中间节点我们可以构造出非常复杂的启动命令树.\n\n#### 注册子节点\n\n中间节点的注册有两个接口\n\n+ `regist_subcmd`用于注册一个已经实例化的子节点\n\n    ```python\n    class A(EntryPoint):\n        pass\n\n    class B(EntryPoint):\n        pass\n\n    a = A()\n\n    b = B()\n\n    a.regist_subcmd(b)\n    ```\n\n+ `regist_sub`用于注册一个子节点类,它会返回被注册的节点的一个实例\n\n    ```python\n    class A(EntryPoint):\n        pass\n\n    class B(EntryPoint):\n        pass\n\n    a = A()\n    b =a.regist_sub(B)\n    ```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpython-tools%2Fschema_entry","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpython-tools%2Fschema_entry","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpython-tools%2Fschema_entry/lists"}