當前位置: 首頁>>代碼示例>>Python>>正文


Python pydantic.create_model方法代碼示例

本文整理匯總了Python中pydantic.create_model方法的典型用法代碼示例。如果您正苦於以下問題:Python pydantic.create_model方法的具體用法?Python pydantic.create_model怎麽用?Python pydantic.create_model使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在pydantic的用法示例。


在下文中一共展示了pydantic.create_model方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: sqlalchemy_to_pydantic

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def sqlalchemy_to_pydantic(
    db_model: Type, *, exclude: Container[str] = []
) -> Type[BaseModel]:
    """
    Mostly copied from https://github.com/tiangolo/pydantic-sqlalchemy
    """
    mapper = inspect(db_model)
    fields = {}
    for attr in mapper.attrs:
        if isinstance(attr, ColumnProperty):
            if attr.columns:
                column = attr.columns[0]
                python_type = column.type.python_type
                name = attr.key
                if name in exclude:
                    continue
                default = None
                if column.default is None and not column.nullable:
                    default = ...
                fields[name] = (python_type, default)
    pydantic_model = create_model(
        db_model.__name__, **fields  # type: ignore
    )
    return pydantic_model 
開發者ID:CTFd,項目名稱:CTFd,代碼行數:26,代碼來源:schemas.py

示例2: test_repeat_base_usage

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_repeat_base_usage():
    class Model(BaseModel):
        a: str

    assert Model.__fields__.keys() == {'a'}

    model = create_model('FooModel', b=1, __base__=Model)

    assert Model.__fields__.keys() == {'a'}
    assert model.__fields__.keys() == {'a', 'b'}

    model2 = create_model('Foo2Model', c=1, __base__=Model)

    assert Model.__fields__.keys() == {'a'}
    assert model.__fields__.keys() == {'a', 'b'}
    assert model2.__fields__.keys() == {'a', 'c'}

    model3 = create_model('Foo2Model', d=1, __base__=model)

    assert Model.__fields__.keys() == {'a'}
    assert model.__fields__.keys() == {'a', 'b'}
    assert model2.__fields__.keys() == {'a', 'c'}
    assert model3.__fields__.keys() == {'a', 'b', 'd'} 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:25,代碼來源:test_create_model.py

示例3: fixture_model_with_path

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def fixture_model_with_path(request):
    class Config:
        arbitrary_types_allowed = True

    ModelWithPath = create_model(
        "ModelWithPath", path=(request.param, ...), __config__=Config
    )
    return ModelWithPath(path=request.param("/foo", "bar")) 
開發者ID:tiangolo,項目名稱:fastapi,代碼行數:10,代碼來源:test_jsonable_encoder.py

示例4: get_pagination_model

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def get_pagination_model(display_model):
    return create_pydantic_model(
        f"PaginationResponse_{display_model.__name__}",
        count=(int, ...),
        next=(Optional[str], None),
        previous=(Optional[str], None),
        result=(List[display_model], ...),
        __base__=BaseModel,
    ) 
開發者ID:MrNaif2018,項目名稱:bitcart,代碼行數:11,代碼來源:utils.py

示例5: validate_args

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def validate_args(spec, location):
    """
    A rough implementation of webargs using pydantic schemas. You can pass a
    pydantic schema as spec or create it on the fly as follows:

    @validate_args({"name": (str, None), "id": (int, None)}, location="query")
    """
    if isinstance(spec, dict):
        spec = create_model("", **spec)

    schema = spec.schema()
    props = schema.get("properties", {})
    required = schema.get("required", [])

    for k in props:
        if k in required:
            props[k]["required"] = True
        props[k]["in"] = location

    def decorator(func):
        # Inject parameters information into the Flask-Restx apidoc attribute.
        # Not really a good solution. See https://github.com/CTFd/CTFd/issues/1504
        apidoc = getattr(func, "__apidoc__", {"params": {}})
        apidoc["params"].update(props)
        func.__apidoc__ = apidoc

        @wraps(func)
        def wrapper(*args, **kwargs):
            data = ARG_LOCATIONS[location]()
            loaded = spec(**data).dict(exclude_unset=True)
            return func(*args, loaded, **kwargs)

        return wrapper

    return decorator 
開發者ID:CTFd,項目名稱:CTFd,代碼行數:37,代碼來源:request.py

示例6: test_invalid_identifiers_signature

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_invalid_identifiers_signature():
    model = create_model(
        'Model', **{'123 invalid identifier!': Field(123, alias='valid_identifier'), '!': Field(0, alias='yeah')}
    )
    assert _equals(str(signature(model)), '(*, valid_identifier: int = 123, yeah: int = 0) -> None')
    model = create_model('Model', **{'123 invalid identifier!': 123, '!': Field(0, alias='yeah')})
    assert _equals(str(signature(model)), '(*, yeah: int = 0, **extra_data: Any) -> None') 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:9,代碼來源:test_model_signature.py

示例7: test_create_model

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_create_model():
    model = create_model('FooModel', foo=(str, ...), bar=123)
    assert issubclass(model, BaseModel)
    assert issubclass(model.__config__, BaseModel.Config)
    assert model.__name__ == 'FooModel'
    assert model.__fields__.keys() == {'foo', 'bar'}
    assert model.__validators__ == {}
    assert model.__config__.__name__ == 'Config' 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:10,代碼來源:test_create_model.py

示例8: test_create_model_usage

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_create_model_usage():
    model = create_model('FooModel', foo=(str, ...), bar=123)
    m = model(foo='hello')
    assert m.foo == 'hello'
    assert m.bar == 123
    with pytest.raises(ValidationError):
        model()
    with pytest.raises(ValidationError):
        model(foo='hello', bar='xxx') 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:11,代碼來源:test_create_model.py

示例9: test_invalid_name

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_invalid_name():
    with pytest.warns(RuntimeWarning):
        model = create_model('FooModel', _foo=(str, ...))
    assert len(model.__fields__) == 0 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:6,代碼來源:test_create_model.py

示例10: test_field_wrong_tuple

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_field_wrong_tuple():
    with pytest.raises(errors.ConfigError):
        create_model('FooModel', foo=(1, 2, 3)) 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:5,代碼來源:test_create_model.py

示例11: test_inheritance

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_inheritance():
    class BarModel(BaseModel):
        x = 1
        y = 2

    model = create_model('FooModel', foo=(str, ...), bar=(int, 123), __base__=BarModel)
    assert model.__fields__.keys() == {'foo', 'bar', 'x', 'y'}
    m = model(foo='a', x=4)
    assert m.dict() == {'bar': 123, 'foo': 'a', 'x': 4, 'y': 2} 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:11,代碼來源:test_create_model.py

示例12: test_custom_config

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_custom_config():
    class Config:
        fields = {'foo': 'api-foo-field'}

    model = create_model('FooModel', foo=(int, ...), __config__=Config)
    assert model(**{'api-foo-field': '987'}).foo == 987
    assert issubclass(model.__config__, BaseModel.Config)
    with pytest.raises(ValidationError):
        model(foo=654) 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:11,代碼來源:test_create_model.py

示例13: test_custom_config_inherits

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_custom_config_inherits():
    class Config(BaseModel.Config):
        fields = {'foo': 'api-foo-field'}

    model = create_model('FooModel', foo=(int, ...), __config__=Config)
    assert model(**{'api-foo-field': '987'}).foo == 987
    assert issubclass(model.__config__, BaseModel.Config)
    with pytest.raises(ValidationError):
        model(foo=654) 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:11,代碼來源:test_create_model.py

示例14: test_custom_config_extras

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_custom_config_extras():
    class Config(BaseModel.Config):
        extra = Extra.forbid

    model = create_model('FooModel', foo=(int, ...), __config__=Config)
    assert model(foo=654)
    with pytest.raises(ValidationError):
        model(bar=654) 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:10,代碼來源:test_create_model.py

示例15: test_inheritance_validators

# 需要導入模塊: import pydantic [as 別名]
# 或者: from pydantic import create_model [as 別名]
def test_inheritance_validators():
    class BarModel(BaseModel):
        @validator('a', check_fields=False)
        def check_a(cls, v):
            if 'foobar' not in v:
                raise ValueError('"foobar" not found in a')
            return v

    model = create_model('FooModel', a='cake', __base__=BarModel)
    assert model().a == 'cake'
    assert model(a='this is foobar good').a == 'this is foobar good'
    with pytest.raises(ValidationError):
        model(a='something else') 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:15,代碼來源:test_create_model.py


注:本文中的pydantic.create_model方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。