【发布时间】:2021-10-07 16:40:11
【问题描述】:
您好,感谢您阅读这篇长文。我正在学习 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 模式中的拼写错误:
date_create: dt.datetime,其他地方都是date_created。 -
谢谢!你是对的!我应该在创建模式时复制和粘贴!
标签: python postgresql sqlalchemy fastapi pydantic