当前位置: 首页>>代码示例>>Python>>正文


Python pydantic.BaseConfig方法代码示例

本文整理汇总了Python中pydantic.BaseConfig方法的典型用法代码示例。如果您正苦于以下问题:Python pydantic.BaseConfig方法的具体用法?Python pydantic.BaseConfig怎么用?Python pydantic.BaseConfig使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pydantic的用法示例。


在下文中一共展示了pydantic.BaseConfig方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_alias_camel_case

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseConfig [as 别名]
def test_alias_camel_case():
    class Model(BaseModel):
        one_thing: int
        another_thing: int

        class Config(BaseConfig):
            @classmethod
            def get_field_info(cls, name):
                field_config = super().get_field_info(name) or {}
                if 'alias' not in field_config:
                    field_config['alias'] = re.sub(r'(?:^|_)([a-z])', lambda m: m.group(1).upper(), name)
                return field_config

    v = Model(**{'OneThing': 123, 'AnotherThing': '321'})
    assert v.one_thing == 123
    assert v.another_thing == 321
    assert v == {'one_thing': 123, 'another_thing': 321} 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:19,代码来源:test_aliases.py

示例2: test_get_field_info_inherit

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseConfig [as 别名]
def test_get_field_info_inherit():
    class ModelOne(BaseModel):
        class Config(BaseConfig):
            @classmethod
            def get_field_info(cls, name):
                field_config = super().get_field_info(name) or {}
                if 'alias' not in field_config:
                    field_config['alias'] = re.sub(r'_([a-z])', lambda m: m.group(1).upper(), name)
                return field_config

    class ModelTwo(ModelOne):
        one_thing: int
        another_thing: int
        third_thing: int

        class Config:
            fields = {'third_thing': 'Banana'}

    v = ModelTwo(**{'oneThing': 123, 'anotherThing': '321', 'Banana': 1})
    assert v == {'one_thing': 123, 'another_thing': 321, 'third_thing': 1} 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:22,代码来源:test_aliases.py

示例3: create_response_field

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseConfig [as 别名]
def create_response_field(
    name: str,
    type_: Type[Any],
    class_validators: Optional[Dict[str, Validator]] = None,
    default: Optional[Any] = None,
    required: Union[bool, UndefinedType] = False,
    model_config: Type[BaseConfig] = BaseConfig,
    field_info: Optional[FieldInfo] = None,
    alias: Optional[str] = None,
) -> ModelField:
    """
    Create a new response field. Raises if type_ is invalid.
    """
    class_validators = class_validators or {}
    field_info = field_info or FieldInfo(None)

    response_field = functools.partial(
        ModelField,
        name=name,
        type_=type_,
        class_validators=class_validators,
        default=default,
        required=required,
        model_config=model_config,
        alias=alias,
    )

    try:
        if PYDANTIC_1:
            return response_field(field_info=field_info)
        else:  # pragma: nocover
            return response_field(schema=field_info)
    except RuntimeError:
        raise fastapi.exceptions.FastAPIError(
            f"Invalid args for response field! Hint: check that {type_} is a valid pydantic field type"
        ) 
开发者ID:tiangolo,项目名称:fastapi,代码行数:38,代码来源:utils.py

示例4: get_missing_field_error

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseConfig [as 别名]
def get_missing_field_error(loc: Tuple[str, ...]) -> ErrorWrapper:
    if PYDANTIC_1:
        missing_field_error = ErrorWrapper(MissingError(), loc=loc)
    else:  # pragma: no cover
        missing_field_error = ErrorWrapper(  # type: ignore
            MissingError(), loc=loc, config=BaseConfig,
        )
    return missing_field_error 
开发者ID:tiangolo,项目名称:fastapi,代码行数:10,代码来源:utils.py

示例5: test_errors_unknown_error_object

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseConfig [as 别名]
def test_errors_unknown_error_object():
    with pytest.raises(RuntimeError):
        list(flatten_errors([object], BaseConfig)) 
开发者ID:samuelcolvin,项目名称:pydantic,代码行数:5,代码来源:test_errors.py

示例6: request_params_to_args

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseConfig [as 别名]
def request_params_to_args(
    required_params: Sequence[ModelField],
    received_params: Union[Mapping[str, Any], QueryParams, Headers],
) -> Tuple[Dict[str, Any], List[ErrorWrapper]]:
    values = {}
    errors = []
    for field in required_params:
        if is_scalar_sequence_field(field) and isinstance(
            received_params, (QueryParams, Headers)
        ):
            value = received_params.getlist(field.alias) or field.default
        else:
            value = received_params.get(field.alias)
        field_info = get_field_info(field)
        assert isinstance(
            field_info, params.Param
        ), "Params must be subclasses of Param"
        if value is None:
            if field.required:
                if PYDANTIC_1:
                    errors.append(
                        ErrorWrapper(
                            MissingError(), loc=(field_info.in_.value, field.alias)
                        )
                    )
                else:  # pragma: nocover
                    errors.append(
                        ErrorWrapper(  # type: ignore
                            MissingError(),
                            loc=(field_info.in_.value, field.alias),
                            config=BaseConfig,
                        )
                    )
            else:
                values[field.name] = deepcopy(field.default)
            continue
        v_, errors_ = field.validate(
            value, values, loc=(field_info.in_.value, field.alias)
        )
        if isinstance(errors_, ErrorWrapper):
            errors.append(errors_)
        elif isinstance(errors_, list):
            errors.extend(errors_)
        else:
            values[field.name] = v_
    return values, errors 
开发者ID:tiangolo,项目名称:fastapi,代码行数:48,代码来源:utils.py

示例7: start_model_server

# 需要导入模块: import pydantic [as 别名]
# 或者: from pydantic import BaseConfig [as 别名]
def start_model_server(model_config: Path,
                       https: Optional[bool] = None,
                       ssl_key: Optional[str] = None,
                       ssl_cert: Optional[str] = None,
                       port: Optional[int] = None) -> None:

    server_params = get_server_params(model_config)

    host = server_params['host']
    port = port or server_params['port']
    model_endpoint = server_params['model_endpoint']
    model_args_names = server_params['model_args_names']

    ssl_config = get_ssl_params(server_params, https, ssl_key=ssl_key, ssl_cert=ssl_cert)

    model = build_model(model_config)

    def batch_decorator(cls: ModelMetaclass) -> ModelMetaclass:
        cls.__annotations__ = {arg_name: list for arg_name in model_args_names}
        cls.__fields__ = {arg_name: ModelField(name=arg_name, type_=list, class_validators=None,
                                               model_config=BaseConfig, required=False, field_info=Field(None))
                          for arg_name in model_args_names}
        return cls

    @batch_decorator
    class Batch(BaseModel):
        pass

    redirect_root_to_docs(app, 'answer', model_endpoint, 'post')

    model_endpoint_post_example = {arg_name: ['string'] for arg_name in model_args_names}

    @app.post(model_endpoint, summary='A model endpoint')
    async def answer(item: Batch = Body(..., example=model_endpoint_post_example)) -> List:
        loop = asyncio.get_event_loop()
        return await loop.run_in_executor(None, interact, model, item.dict())

    @app.post('/probe', include_in_schema=False)
    async def probe(item: Batch) -> List[str]:
        loop = asyncio.get_event_loop()
        return await loop.run_in_executor(None, test_interact, model, item.dict())

    @app.get('/api', summary='Model argument names')
    async def api() -> List[str]:
        return model_args_names

    uvicorn.run(app, host=host, port=port, log_config=log_config, ssl_version=ssl_config.version,
                ssl_keyfile=ssl_config.keyfile, ssl_certfile=ssl_config.certfile, timeout_keep_alive=20) 
开发者ID:deepmipt,项目名称:DeepPavlov,代码行数:50,代码来源:server.py


注:本文中的pydantic.BaseConfig方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。