python - 日期时间的验证错误
问题描述
您好,感谢您阅读长篇文章。我正在学习 FastAPI-SQLAlchemy-PostgresSQL。我正在按照教程编写演示项目。我的数据库是这样创建的:
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title text,
content text,
owner_id integer REFERENCES users(id),
date_created timestamp without time zone,
date_last_updated timestamp without time zone
);
-- Indices -------------------------------------------------------
CREATE UNIQUE INDEX posts_pkey ON posts(id int4_ops);
我的 SQLAlchemy 模型如下所示:
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True, index=True)
title = Column(String, index=True)
content = Column(String, index=True)
owner_id = Column(Integer, ForeignKey('users.id'))
date_created = Column(DateTime, default=dt.datetime.now)
date_last_updated = Column(DateTime, default=dt.datetime.now)
owner = relationship("User", back_populates="posts")
Pydantic Schema 看起来像这样:
class PostBase(BaseModel):
title: str
content: str
class PostCreate(PostBase):
pass
class Post(PostBase):
id: int
owner_id: int
date_create: dt.datetime
date_last_updated: dt.datetime
class Config:
orm_mode = True
最后我用这个创建了一个帖子:
def create_post(db: Session, post: schemas.PostCreate, user_id: int):
post = models.Post(**post.dict(), owner_id=user_id)
db.add(post)
db.commit()
db.refresh(post)
return post
@app.post("/users/{user_id}/posts", response_model=schemas.Post)
def create_post(user_id: int, post: schemas.PostCreate, db: Session = Depends(get_db)):
user = crud.get_user(user_id=user_id, db=db)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return create_post(db=db, post=post, user_id=user_id)
我可以看到该帖子已在数据库中正确创建:| 编号 | 标题|内容|owner_id|创建日期|date_last_updated | | -- | -----|--------|--------|--------------------------| --------------------------| | 3 | 嗨 |嗨 |3 |2021-10-08 03:00:43.731416|2021-10-08 03:00:43.73143|
但是控制台打印以下错误并且 API 没有返回 JSON
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 375, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
return await self.app(scope, receive, send)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/applications.py", line 208, in __call__
await super().__call__(scope, receive, send)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/applications.py", line 112, in __call__
await self.middleware_stack(scope, receive, send)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 580, in __call__
await route.handle(scope, receive, send)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 241, in handle
await self.app(scope, receive, send)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/starlette/routing.py", line 52, in app
response = await func(request)
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 234, in app
response_data = await serialize_response(
File "/Users/jzz/opt/anaconda3/lib/python3.8/site-packages/fastapi/routing.py", line 137, in serialize_response
raise ValidationError(errors, field.type_)
pydantic.error_wrappers.ValidationError: 1 validation error for Post
response -> date_create
field required (type=value_error.missing)
解决方案
pydantic.error_wrappers.ValidationError: 1 validation error for Post
response -> date_create
field required (type=value_error.missing)
这是您的错误,您没有填写一个字段,并且是表单所必需的。
检查date_created
您的表格中是否需要。
推荐阅读
- python - 在 DRF 中的帖子上更新点赞
- javascript - 如何将 JSON 配置文件保存到用户的谷歌驱动器并再次检索它?
- android - android库项目中的DI
- django - 来自 Angular8 的发布数据包含空的 QueryDict 但 Django 中 request.body 中的数据
- django - 根据 django ORM 中的喜欢和评论将帖子划分为动态类别
- c++ - 如何使用地图对文本进行编码?
- json - 如何使用 SQL 确定父对象中 JSON 对象的数量
- windows - Autohotkey (ahk) GUI 十字准线实现
- c# - 在 MVC 中设置数据绑定 Dropdownlist 的默认值
- flutter - connectedResult 在颤振应用程序的启动中返回null?