I am currently working on an API which is using FastAPI, it is mainly used for adding sensor data into my mongodb database. I also want to add a timestamp (for CET) which is automatically written into the mongodb database with the sensor data.
class DataModel(BaseModel):
id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
loc: str
sensor: str
temp: float
humi: float
press: float
power: float
timestamp: datetime = Field(default_factory=(datetime.utcnow() timedelta(hours=1)))
class Config:
allow_population_by_field_name = True
arbitrary_types_allowed = True
json_encoders = {ObjectId: str}
Everything is working fine except the timestamp. This error occurs:
{
"detail": [
{
"loc": [
"body"
],
"msg": "'datetime.datetime' object is not callable",
"type": "type_error"
}
]
}
I hope you have an idea what the possible problem could be.
{
"_id": "637b80a052feee6809711f2c",
"loc": "Mödling",
"sensor": "BME680",
"temp": 5.0,
"humi": 60.0,
"press": 1000.0,
"timestamp": "2022-11-21T13:44:00.371512"
},
This is the output when im only using datetime.utcnow without the brackets and without the timedelta. When I am using datetime.utcnow() without the timedelta the same problem occurs.
CodePudding user response:
default_factory
should be a function, and you are giving a datetime.datetime
type
Do a lambda function:
timestamp: datetime = Field(default_factory= lambda : (datetime.utcnow() timedelta(hours=1)))