跳转到主要内容

基于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-py3-none-any.whl (44.6 kB 查看散列)

上传 Python 3

支持者