[英]Python [pydantic] - Date validation
i'd like to valid a json input for dates as pydantic class, next, to simply inject the file to Mongo.我想验证日期的 json 输入为 pydantic class,接下来,只需将文件注入 Mongo。
Simple class with date type带日期类型的简单 class
class CustomerBase(BaseModel):
birthdate: date = None
Using motor for working with Mongo使用电机与 Mongo 一起工作
Db configuration:数据库配置:
from motor.motor_asyncio import AsyncIOMotorClient
DB = DB_CLIENT[CONF.get("databases", dict())["mongo"]["NAME"]]
8/03/2021 - Update: 2021 年 8 月 3 日 - 更新:
I did the following debug test, first print the class to see how it saved and next try to inject it to Mongo.我做了以下调试测试,首先打印 class 以查看它是如何保存的,然后尝试将其注入 Mongo。
so for input:所以输入:
{ "birthdate": "2021-03-05"}
Routing:路由:
@customers_router.post("/", response_model=dict)
async def add_customer(customer: CustomerBase):
print(customer.dict())
>> {'birthdate': datetime.date(2021, 3, 5)}
await DB.customer.insert_one(customer.dict())
return {"test":1}
>>
File "./customers/routes.py", line 74, in add_customer
await DB.customer.insert_one(customer.dict())
File "/usr/local/lib/python3.8/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/local/lib/python3.8/site-packages/pymongo/collection.py", line 698, in insert_one
self._insert(document,
File "/usr/local/lib/python3.8/site-packages/pymongo/collection.py", line 613, in _insert
return self._insert_one(
File "/usr/local/lib/python3.8/site-packages/pymongo/collection.py", line 602, in _insert_one
self.__database.client._retryable_write(
File "/usr/local/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1498, in _retryable_write
return self._retry_with_session(retryable, func, s, None)
File "/usr/local/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1384, in _retry_with_session
return self._retry_internal(retryable, func, session, bulk)
File "/usr/local/lib/python3.8/site-packages/pymongo/mongo_client.py", line 1416, in _retry_internal
return func(session, sock_info, retryable)
File "/usr/local/lib/python3.8/site-packages/pymongo/collection.py", line 590, in _insert_command
result = sock_info.command(
File "/usr/local/lib/python3.8/site-packages/pymongo/pool.py", line 699, in command
self._raise_connection_failure(error)
File "/usr/local/lib/python3.8/site-packages/pymongo/pool.py", line 683, in command
return command(self, dbname, spec, slave_ok,
File "/usr/local/lib/python3.8/site-packages/pymongo/network.py", line 120, in command
request_id, msg, size, max_doc_size = message._op_msg(
File "/usr/local/lib/python3.8/site-packages/pymongo/message.py", line 714, in _op_msg
return _op_msg_uncompressed(
bson.errors.InvalidDocument: cannot encode object: datetime.date(2021, 3, 5), of type: <class 'datetime.date'>
Issues: 1.The date in class saved as birthday: datetime.date(2021, 3, 5) is that expected?问题: 1.class 中的日期保存为生日: datetime.date(2021, 3, 5) 是预期的吗? 2.Surely the problem coming from: ''' DB.customer.insert_one(customer.dict()) ''' it does work when i change the date type to str in Class 2.问题肯定来自: ''' DB.customer.insert_one(customer.dict()) ''' 当我在 Class 中将日期类型更改为 str 时,它确实有效
Update 09/03/2022: 2022 年 9 月 3 日更新:
following Tom's suggestion: the decorator and parse_birthday function added.按照汤姆的建议:添加了装饰器和 parse_birthday function。 Now i able to document to Mongo but not able to read it.现在我可以记录到 Mongo 但无法阅读它。
class CustomerBase(BaseModel):
birthdate: datetime.date
@validator("birthdate", pre=True)
def parse_birthdate(cls, value):
return datetime.datetime.strptime(
value,
"%d/%m/%Y"
).date()
def dict(self, *args, **kwargs) -> 'DictStrAny':
for_mongo = kwargs.pop('for_mongo', False)
d = super().dict(*args, **kwargs)
if for_mongo:
for k, v in d.items():
if isinstance(v, datetime.date):
d[k] = datetime.datetime(
year=v.year,
month=v.month,
day=v.day,
)
return d
class CustomerOnDB(CustomerBase):
id_: str
assign data (working): input: {"birthdate": "01/11/1978"}分配数据(工作):输入:{“birthdate”:“01/11/1978”}
@customers_router.post("/", response_model=dict )
async def add_customer(customer: CustomerBase):
customer_op = await DB.customer.insert_one(customer.dict(for_mongo=True))
if customer_op.inserted_id:
#customer_op.inserted_id -> is the str _id
await _get_customer_or_404(customer_op.inserted_id)
return { "id_": str(customer_op.inserted_id) }
When trying to read:尝试阅读时:
def validate_object_id(id_: str):
try:
_id = ObjectId(id_)
except Exception:
raise HTTPException(status_code=400)
return _id
@customers_router.get(
"/{id_}",
response_model=CustomerOnDB
)
async def get_customer_by_id(id_: ObjectId = Depends(validate_object_id)):
customer = await DB.customer.find_one({"_id": id_})
if customer:
customer["id_"] = str(customer["_id"])
return customer
else:
raise HTTPException(status_code=404, detail="Customer not found")
Getting:得到:
File "/usr/local/lib/python3.8/site-packages/fastapi/routing.py", line 126, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for CustomerOnDB
response -> 0 -> birthdate
strptime() argument 1 must be str, not datetime.datetime (type=type_error)
I'm not sure what your question is as your CustomerBase
works fine with我不确定您的问题是什么,因为您的CustomerBase
可以正常使用
{ "birthdate": "2021-03-05"}
this input. { "birthdate": "2021-03-05"}
这个输入。
If you want to parse %d/%m/%Y
date, parse it using validator and pre
parameter.如果要解析%d/%m/%Y
日期,请使用验证器和pre
参数对其进行解析。
class CustomerBase(BaseModel):
birthdate: date
@validator("birthdate", pre=True)
def parse_birthdate(cls, value):
return datetime.datetime.strptime(
value,
"%d/%m/%Y"
).date()
EDIT: You added a comment mentioning something else that doesn't work as you expect.编辑:您添加了一条评论,提到了其他无法按预期工作的内容。 AFAIK mongo doesn't accept datetime.date
. AFAIK mongo 不接受datetime.date
。 Just change it to datetime.datetime
when dumping to dict or change type to datetime
.转储到 dict 或将类型更改为datetime.datetime
时,只需将其更改为datetime
。
example例子
import datetime
from pydantic.main import BaseModel
class CustomerBase(BaseModel):
birthdate: datetime.date
def dict(self, *args, **kwargs) -> 'DictStrAny':
d = super().dict(*args, **kwargs)
for k, v in d.items():
if isinstance(v, datetime.date):
d[k] = datetime.datetime(
year=v.year,
month=v.month,
day=v.day,
)
return d
If you need both functionalities如果您需要这两种功能
import datetime
from pydantic import validator
from pydantic.main import BaseModel
class CustomerBase(BaseModel):
birthdate: datetime.date
@validator("birthdate", pre=True)
def parse_birthdate(cls, value):
return datetime.datetime.strptime(
value,
"%d/%m/%Y"
).date()
def dict(self, *args, **kwargs) -> 'DictStrAny':
for_mongo = kwargs.pop('for_mongo', False)
d = super().dict(*args, **kwargs)
if for_mongo:
for k, v in d.items():
if isinstance(v, datetime.date):
d[k] = datetime.datetime(
year=v.year,
month=v.month,
day=v.day,
)
return d
>>> c = CustomerBase(**{"birthdate": "03/05/2021"})
>>> c.dict()
>>> {'birthdate': datetime.date(2021, 5, 3)}
>>> c.dict(for_mongo=True)
>>> {'birthdate': datetime.datetime(2021, 5, 3, 0, 0)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.