I have setup a simple class in Python with a member posted that defaults to utcnow() time as a string. However when I create an instance of the class then create another instance a few minutes later they both have the exact same posted time.
If in the route I have created I pass in posted=str(datetime.utcnow()) it works fine so Python is picking up the computer datetime correctly. I have also tested this on a Heroku app I have running and I get the same problem.
The time it puts in is the time the app was first run as if it's being treated as a static value.
import uuid
from datetime import datetime
from typing import Dict
from dataclasses import dataclass, field
from models.model import Model
#dataclass
class Dummy(Model):
collection: str = field(init=False, default='dummy')
text: str
posted: str = field(default=str(datetime.utcnow()))
_id: str = field(default_factory=lambda: uuid.uuid4().hex)
def json(self) -> Dict:
return {
"text": self.text,
"posted": self.posted,
"_id": self._id
}
You could use default_factory instead in case you want a dynamically default value.
#dataclass
class Dummy(Model):
...
posted: str = field(default_factory=lambda: str(datetime.utcnow()))
Related
When using FastApi with a pydantic model at the reponse model, I found that the uuid are always returned lowercase by the http response. Is there any standard way to return them upper cased?
from fastapi import FastAPI
from pydantic import BaseModel
from uuid import UUID
app = FastAPI()
class Test(BaseModel):
ID: UUID
#app.get("/test", response_model=Test)
async def test():
id_ = uuid.uuid4()
return Test(ID=id_)
When making the request the returned uuid will be in lowercased.
from requestr
a = requests.get("http://localhost:800/test").text # you ir
# a -> '{"ID":"fffc0b5b-8e8d-4d06-b910-2ae8d616166c"}' # it is lowercased
The only somewhat hacky way I found to return them uppercased is overwriting the uuid class __str__ method or sub-classing uuid:
What I tried (and works):
# use in main.py when importing for first time
def newstr(self):
hex = '%032x' % self.int
return ('%s-%s-%s-%s-%s' % (hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])).upper()
uuid.UUID.__str__ = newstr
But I was wondering if there is a standard way of doing this without modifying the original class, maybe a post process in pydantic or a setting in FastApi.
You can define custom json_encoders:
class Test(BaseModel):
ID: UUID
class Config:
json_encoders = {
UUID: lambda val: str(val).upper()
}
I am new to fastapi and SQLModel, i was trying to implement some basic code from my existing lib, I have an Address Class
like
#dataclass
class Address(DataClassJsonMixin):
addr1: str
city: str
province: str
I simply want to create a class in SQLModel that connects to DB. I have only added a new column ID here. i am getting below error where i am not sure why is it asking for a config attribute.
class AddressMaster(SQLModel, Address):
id: int = Field(default=None, primary_key=True)
AttributeError: type object 'Address' has no attribute '__config__'
It's failing on config = getattr(base, "__config__") that has some information which I am not able to comprehand.
# Only one of the base classes (or the current one) should be a table model
# this allows FastAPI cloning a SQLModel for the response_model without
# trying to create a new SQLAlchemy, for a new table, with the same name, that
# triggers an error
try 1:
from sqlmodel import SQLModel, Field
from ...core import Address
from dataclasses import dataclass
#dataclass
class AddressDB(Address, SQLModel):
pass
# END AddressDB
class AddressMaster(AddressDB, table=True):
"""
Address Master Table
"""
id: int = Field(default=None, primary_key=True)
# END AddressMaster
Object Creation
objAd = AddressMaster.from_dict({"addr1": "Kashmir", "city": "Srinagar", "province": "Kashmir"})
There is an error in the semantics of your AdressMaster class.
If it is meant to be a class related to your DB. Then you have to specify in the first parameter either the class inheriting from a SQL model or from SQLmodel (And in this case, you should rewrite each attribute of your model within this class) directly. And it is necessary to pass it the argument table=True
class AddressMaster(Address, table=True):
id: int = Field(default=None, primary_key=True)
# Here the attributes will be inherited from your Adress class
# (provided that this one in its parentage is an inheritance link with a modelSQL)
Or
class AddressMaster(SQLModel, table=True):
id: int = Field(default=None, primary_key=True)
addr1: str
city: str
province: str
# Here, the class is independent from the other pydantic
# validation models since it inherits directly from SQLModel
In Try 1:
You are trying to pass two parameters to your AddressDB class, one of which is an SQLModel. However, SQLModel allows to override SQLAlchemy, and accepts as parameter only models from SQLAlchemy or Pydantic. During the initialization, it goes through the arguments passed in parameter and tries to call the method or attribute Config which exists in the pydantic and SQLAlchemy models. This is the source of your error since you pass in parameter a DataClassJsonMixin which has no Config method or attribute. This is the origin of your error.
How to solve it. You just have to not call DataClassJsonMixin which seems to me to encode / decode JSON data. However, this is a basic behavior of Pydantic (which is used behind SQLModel).
So if you use the first method shown above (i.e. inherited from a SQLModel), you just have to put your validation fields inside AddressDB and make this class inherit only from SQLModel
class AddressDB(SQLModel):
addr1: str
city: str
province: str
I have a base class BaseTemplateData which inherits from pydantic.BaseModel. Then, I want to have a property of the BaseTemplate class which stores a type of a child class of BaseTemplateData.
I'm doing the following, but I'm getting a mypy error saying Type variable "file.path.TemplateDataType" is unbound, when I'm explicitly passing a bound parameter to the TypeVar call.
I also would like to have another class BaseTemplate2 which property doesn't store the type itself, but an instance of a child class of BaseTemplateData. Would the approach be correct?
Any help would be much appreciated. Thanks!
from typing import Type, TypeVar
from pydantic import BaseModel
class BaseTemplateData(BaseModel):
"""
Base class for all templates.
"""
TemplateDataType = TypeVar("TemplateDataType", bound=BaseTemplateData)
class BaseTemplate(BaseModel):
"""
Template class for email templates
"""
data_model: Type[TemplateDataType]
class BaseTemplate2(BaseModel):
"""
Template class for email templates 2
"""
data_model: TemplateDataType
I'm not so familiar with pythons Typing and can't imagine what you trying to solve by this code. But I don't understand why you need TemplateDataType?
Your expectations are:
I want to have a property of the BaseTemplate class which stores a type of a child class of BaseTemplateData
I also would like to have another class BaseTemplate2 which property doesn't store the type itself, but an instance of a child class of BaseTemplateData
Okay:
from typing import Type
from pydantic import BaseModel
class BaseTemplateData(BaseModel):
"""
Base class for all templates.
"""
class ChildBaseTemplateData(BaseTemplateData):
"""
Child class for Base class.
"""
class BaseTemplate(BaseModel):
"""
Template class for email templates
"""
data_model: Type[BaseTemplateData]
class BaseTemplate2(BaseModel):
"""
Template class for email templates 2
"""
data_model: BaseTemplateData
a = BaseTemplate()
# it is okay. Because a.data_model is a "type of a child class of BaseTemplateData"
a.data_model = ChildBaseTemplateData
b = BaseTemplate2()
# it is okay too. Because b.data_model is "an instance of a child class of BaseTemplateData"
b.data_model = ChildBaseTemplateData()
c = BaseTemplate2()
# error: Incompatible types in assignment (expression has type "str", variable has type "BaseTemplateData")
c.data_model = "string"
Here is a good explanation about TypeVar
Also TypeVar is using with Generics.
Here is no Generics in your example
Proper usage of TypeVar will be something like:
from typing import Type, TypeVar, Generic
A = TypeVar("A", int, str)
class B(Generic[A]):
pass
# Ok
a = B[int]
# Error: error: Value of type variable "A" of "B" cannot be "float"
b = B[float]
I'm a little new to tinkering with class inheritance in python, particularly when it comes down to using class attributes. In this case I am using a class attribute to change an argument in pydantic's Field() function. This wouldn't be too hard to do if my class contained it's own constructor, however, my class User1 is inheriting this from pydantic's BaseModel.
The idea is that I would like to be able to change the class attribute prior to creating the instance.
Please see some example code below:
from pydantic import Basemodel, Field
class User1(BaseModel):
_set_ge = None # create class attribute
item: float = Field(..., ge=_set_ge)
# avoid overriding BaseModel's __init__
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
User1._set_ge = 0 # setting the class attribute to a new value
instance = User1(item=-1)
print(instance) # item=-1.0
When creating the instance using instance = User1(item=-1) I would expect a validation error to be thrown, but it instead passes validation and simply returns the item value.
If I had my own constructor there would be little issue in changing the _set_ge, but as User1 inheriting this constructor from BaseModel, things are a little more complicated.
The eventual aim is to add this class to a fastapi endpoint as follows:
from fastapi import Fastapi
from schemas import User1
class NewUser1(User1):
pass
NewUser1._set_ge = 0
#app.post("/")
def endpoint(request: NewUser1):
return User1.item
To reduce code duplication, I aimed to use this method to easily change Field() arguments. If there is a better way, I'd be glad to consider that too.
This question is quite closely related to this unanswered one.
In the end, the #validator proposal by #hernán-alarcón is probably the best way to do this. For example:
from pydantic import Basemodel, Field, NumberNotGeError
from typing import ClassVar
class User(BaseModel):
_set_ge = ClassVar[float] # added the ClassVar typing to make clearer, but the underscore should be sufficient
item: float = Field(...)
#validator('item')
def limits(cls, v):
limit_number = cls._set_ge
if v >= limit_number:
return v
else:
raise NumberNotGeError(limit_value=limit_number)
class User1(User)
_set_ge = 0 # setting the class attribute to a new value
instance = User1(item=-1) # raises the error
I want to include a custom class into a route's response. I'm mostly using nested pydantic.BaseModels in my application, so it would be nice to return the whole thing without writing a translation from the internal data representation to what the route returns.
As long as everything inherits from pydantic.BaseModel this is trivial, but I'm using a class Foo in my backend which can't do that, and I can't subclass it for this purpose either. Can I somehow duck type that class's definition in a way that fastapi accepts it? What I have right now is essentially this:
main.py
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Foo:
"""Foo holds data and can't inherit from `pydantic.BaseModel`."""
def __init__(self, x: int):
self.x = x
class Response(BaseModel):
foo: Foo
# plus some more stuff that doesn't matter right now because it works
#app.get("/", response_model=Response)
def root():
return Response(foo=Foo(1))
if __name__ == '__main__':
import uvicorn
uvicorn.run("main:app") # RuntimeError
It's not documented, but you can make non-pydantic classes work with fastapi. What you need to do is:
Tell pydantic that using arbitrary classes is fine. It
will try to jsonify them using vars(), so only straight forward
data containers will work - no using property, __slots__ or stuff like that[1].
Create a proxy BaseModel, and tell Foo to offer it if someone
asks for its schema - which is what fastapis OpenAPI pages do.
I'll just assume that you want them to work too since they're
amazing.
main.py
from fastapi import FastAPI
from pydantic import BaseModel, BaseConfig, create_model
app = FastAPI()
BaseConfig.arbitrary_types_allowed = True # change #1
class Foo:
"""Foo holds data and can't inherit from `pydantic.BaseModel`."""
def __init__(self, x: int):
self.x = x
__pydantic_model__ = create_model("Foo", x=(int, ...)) # change #2
class Response(BaseModel):
foo: Foo
#app.get("/", response_model=Response)
def root():
return Response(foo=Foo(1))
if __name__ == '__main__':
import uvicorn
uvicorn.run("main:app") # works
[1] If you want more complex jsonification, you need to provide it to the Response class explicitly via Config.json_encoders.
Here is a full implementation using a subclass with validators and extra schema:
from psycopg2.extras import DateTimeTZRange as DateTimeTZRangeBase
from sqlalchemy.dialects.postgresql import TSTZRANGE
from sqlmodel import (
Column,
Field,
Identity,
SQLModel,
)
from pydantic.json import ENCODERS_BY_TYPE
ENCODERS_BY_TYPE |= {DateTimeTZRangeBase: str}
class DateTimeTZRange(DateTimeTZRangeBase):
#classmethod
def __get_validators__(cls):
yield cls.validate
#classmethod
def validate(cls, v):
if isinstance(v, str):
lower = v.split(", ")[0][1:].strip().strip()
upper = v.split(", ")[1][:-1].strip().strip()
bounds = v[:1] + v[-1:]
return DateTimeTZRange(lower, upper, bounds)
elif isinstance(v, DateTimeTZRangeBase):
return v
raise TypeError("Type must be string or DateTimeTZRange")
#classmethod
def __modify_schema__(cls, field_schema):
field_schema.update(type="string", example="[2022,01,01, 2022,02,02)")
class EventBase(SQLModel):
__tablename__ = "event"
timestamp_range: DateTimeTZRange = Field(
sa_column=Column(
TSTZRANGE(),
nullable=False,
),
)
class Event(EventBase, table=True):
id: int | None = Field(
default=None,
sa_column_args=(Identity(always=True),),
primary_key=True,
nullable=False,
)
as per #Arne 's solution you need to add your own validators and schema if the Type you are using has __slots__ and basically no way to get out a dict.
Link to Github issue: https://github.com/tiangolo/sqlmodel/issues/235#issuecomment-1162063590