當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。