Pydantic: dataclass vs BaseModel

Your question is answered in Pydantic’s documentation, specifically: Keep in mind that pydantic.dataclasses.dataclass is a drop-in replacement for dataclasses.dataclass with validation, not a replacement for pydantic.BaseModel (with a small difference in how initialization hooks work). There are cases where subclassing pydantic.BaseModel is the better choice. For more information and discussion see samuelcolvin/pydantic#710. The discussion link … Read more

How to pass the default value to a variable if None was passed?

You need to enable validate_assignment option in model config: from typing import Optional from pydantic import BaseModel, validator class User(BaseModel): name: Optional[str] = ” password: Optional[str] = ” class Config: validate_assignment = True @validator(‘name’) def set_name(cls, name): return name or ‘foo’ user = User(name=None, password=’some_password’, ) print(“Name is “, user.name) user.name = None print(“Name is … Read more

How to give a Pydantic list field a default value?

For pydantic you can use mutable default value, like: class Foo(BaseModel): defaulted_list_field: List[str] = [] f1, f2 = Foo(), Foo() f1.defaulted_list_field.append(“hey!”) print(f1) # defaulted_list_field=[‘hey!’] print(f2) # defaulted_list_field=[] It will be handled correctly (deep copy) and each model instance will have its own empty list. Pydantic also has default_factory parameter. In the case of an empty … Read more

Pydantic enum field does not get converted to string

You need to use use_enum_values option of model config: use_enum_values whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialise model.dict() later (default: False) from enum import Enum from pydantic import BaseModel class S(str, Enum): am=’am’ pm=’pm’ class K(BaseModel): k:S z:str … Read more

How to read body as any valid json?

You can find nearly everything inside the Request object You are able to get request body with request.json(), which will give you the parsed JSON as dictionary. from fastapi import Request, FastAPI @app.post(“/dummypath”) async def get_body(request: Request): return await request.json() If you want access the body as string, you can use request.body()

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)