基于JSON Schema生成Python类型的工具
项目描述
JSON Schema生成Python类型
基于JSON Schema生成Python类型(基于TypedDict)的工具
快速入门
安装
python3 -m pip install --user jsonschema-gentypes
将JSON schema转换为包含类型的Python文件
jsonschema-gentypes --json-schema=<JSON schema> --python=<destination Python file>
配置文件
您也可以编写一个名为jsonschema-gentypes.yaml
的配置文件
headers: >
# Automatically generated file from a JSON schema
# Used to correctly format the generated file
callbacks:
- - black
- - isort
generate:
- # JSON schema file path
source: jsonschema_gentypes/schema.json
# Python file path
destination: jsonschema_gentypes/configuration.py
# The name of the root element
root_name: Config
# Argument passed to the API
api_arguments:
additional_properties: Only explicit
# Rename an element
name_mapping: {}
# The minimum Python version that the code should support. By default the
# currently executing Python version is chosen. Note that the output
# may require typing_extensions to be installed.
python_version: '3.11'
然后只需运行
jsonschema-gentypes
默认
默认值被导出到Python文件中,然后您可以进行如下操作
value_with_default = my_object.get('field_name', my_schema.FIELD_DEFAULT)
限制
需要Python 3.8
请参阅带有“限制”标签的问题。
pre-commit钩子
该项目提供了预提交钩子来自动生成文件。
repos:
- repo: https://github.com/camptocamp/jsonschema-gentypes
rev: <version> # Use the ref you want to point at
hools:
- id: jsonschema-gentypes
files: |
(?x)^(
jsonschema-gentypes\.yaml|
<schema_path>\.json
)$
请参阅配置中的pre_commit部分,以在生成后立即运行pre-commit,例如
pre_commit:
enabled: true
arguments:
- --color=never
OpenAPI3
我们还可以为OpenAPI3模式生成类型(自动检测)。
我们示例中的结果可以用于金字塔,例如
import pyramid.request
from pyramid.view import view_config
from openaoi3 import *
def open_api(func):
def wrapper(request: pyramid.request.Request, **kwargs) -> Any:
typed_request = {}
try:
typed_request{'request_body'} = request.json
except Exception as e:
pass
typed_request{'path'} = request.matchdict
typed_request{'query'} = request.params
return = func(request, request_typed=typed_request, **kwargs)
return wrapper
@view_config(route_name="route_name", renderer="json")
@open_api
def view(
request: pyramid.request.Request,
request_typed: OgcapiCollectionsCollectionidGet,
) -> OgcapiCollectionsCollectionidGetResponse:
return {...}
贡献
安装预提交钩子
pip install pre-commit
pre-commit install --allow-missing-config
prospector
测试应该通过。
代码应该进行类型检查。
代码应该使用 pytests
进行测试。
项目详情
下载文件
下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于 安装软件包 的信息。
源代码分发
jsonschema_gentypes-2.8.1.tar.gz (28.4 kB 查看散列)
构建分发
关闭
jsonschema_gentypes-2.8.1.tar.gz 的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | 88f0d92ac1ab3d9bc7acd3891038c1ad13ecbbe26a31b6a0c13f088053c69ca6 |
|
MD5 | 82dbf4313d6bd4e4b8543aee6a05c816 |
|
BLAKE2b-256 | 57de959f04148460fa938252f1027e3373821960a440b349e5da20ca515cc6dc |
关闭
jsonschema_gentypes-2.8.1-py3-none-any.whl 的散列
算法 | 散列摘要 | |
---|---|---|
SHA256 | 4438bd3ba2096e6357a4a1d0c76de909f40c0ad3f0ffc86f442aa3ffcf7ce028 |
|
MD5 | d20f48db836df4c4ef385932a41f2340 |
|
BLAKE2b-256 | 93cbf46dc91a864fea4dc28756a552fa563c95bea27a30d6131ede75ce8f3106 |