- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我开始在 python 和 sqlalchemy 中使用 FastAPI 构建一个 api :这是模型的一部分:
class Game(Base):
__tablename__ = "games"
id = Column(Integer, primary_key=True, index=True)
league_id = Column(Integer)
radiant_score = Column(Integer)
dire_score = Column(Integer)
duration = Column(Integer)
is_valid = Column(Boolean, default=True)
playerstats = relationship("PlayerStat", back_populates="match")
class PlayerStat(Base):
__tablename__ = "playerstats"
match_id = Column(Integer, ForeignKey("games.id"), primary_key=True)
slot = Column(Integer, primary_key=True)
hero_id = Column(Integer, ForeignKey("heros.id"))
num_kills = Column(Integer, default=None)
isRadiant = Column(Boolean, default=None)
match = relationship("Game", back_populates="playerstats")
heros = relationship("Hero", back_populates="playerstats")
此后,我为 pydantic 创建模式/模型(请原谅长部分):
class PlayerStatBase(BaseModel):
slot: int
hero_id: int
num_kills: int
isRadiant: bool
class PlayerStatCreate(PlayerStatBase):
pass
class PlayerStat(PlayerStatBase):
slot: int
hero_id: int
num_kills: int
isRadiant: bool
class Config:
orm_mode = True
class GameBase(BaseModel):
id: int
league_id: int
radiant_score: int
dire_score: int
duration: int
is_valid: bool
class GameCreate(GameBase):
pass
class Game(GameBase):
id: int
league_id: int
radiant_score: int
dire_score: int
duration: int
is_valid: bool
players: List[PlayerStat] = [{}]
class Config:
orm_mode = True
以及我与 api 一起使用的 crud 函数:
def get_match(db: Session, match_id: int):
print(db.query(models.Game).filter(models.Game.id == match_id))
return db.query(models.Game).filter(models.Game.id == match_id).first()
API 路由是:
@app.get("/matches/{match_id}", response_model=schemas.Game)
def read_game(match_id: int, db: Session = Depends(get_db)):
db_game = crud.get_match(db, match_id=match_id)
if db_game is None:
raise HTTPException(status_code=404, detail="Game not found")
return db_game
我得到的结果是下一个:
{
"id": 1,
"league_id": 10,
"radiant_score": 41,
"dire_score": 5,
"duration": 3541,
"is_valid": true,
"players": [
{}
]
}
我想用相应比赛的玩家统计列表(按插槽排序)填充“玩家”,如下所示:
"players" : [
{
"slot": 0,
"hero_id": 14,
"num_kills": 54,
"isRadiant": true
},
{
"slot": 1,
"hero_id": 15,
"num_kills": 1,
"isRadiant": false
}
]
我认为我需要尝试模型/架构或 CRUD 函数之一,但真的不知道是哪一个?另外,也许有一些无用或构建不良的 pydantic 模式
PS:我遵循了 FastAPI 文档的指南(我建议阅读)。
感谢您的帮助!
最佳答案
我相信你的问题不在于fastapi的范围内,而是在于sqlalchemy的范围内。 当您查询具有关系的 orm 对象时,fastapi 的标准是在访问关系时延迟加载关系。由于您从不直接访问关系playerstats,因此它不会加载。请参阅 the docs获取信息。
问题的解决方案应该是将 crud 函数更新为:
return db.query(models.Game).filter(models.Game.id == match_id)
.options(selectinload(models.Game.playerstats)).first()
“Select In Load”是一种急切加载类型,它将在提交查询时加载关系。如果您希望每个查询都发生此行为,您可以将 orm 更新为:
playerstats = relationship("PlayerStat", back_populates="match", lazy="selectin")
我希望这有帮助。这是我在 stackoverflow 上的第一个答案:)
编辑:实际上还有另一件事。在您的 orm 中,这种关系称为“playerstats”,而您在 pydantic 模型中将属性命名为“players”。那是行不通的。将 pydantic 属性名称从“players”更改为“playerstats”,现在一切都应该可以正常工作。
编辑 2:正如您所猜测的,一切都还不能正常工作。我刚刚发现还缺少一件事。在 pydantic 模型中,您可以设置 orm 选项。这在使用 sqlalchemy 时非常重要。我向您所有的 pydantic 模型推荐这个。 必须在每个 pydantic 模型及其属性模型上进行设置
class OtherModel(BaseModel):
value: str = None
class Config:
orm_mode = True
class SomePydanticModel(BaseModel):
value: str = None
some_other_model: OtherModel = None
class Config:
orm_mode = True
现在我们还可以再次修改你的 crud 方法的 return 语句:
return Game.from_orm(db.query(models.Game).options(selectinload(models.Game.playerstats)).filter(models.Game.id == match_id).first())
现在一切终于应该可以正常工作了:)
关于python-3.x - 使用 FastAPI 从 get 请求添加更多数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64741222/
我正在研究最适合我的 Web 框架。 我们将开发几个微服务,我们需要在一些微服务上分派(dispatch)事件,这些事件可以在其他微服务上监听。 是否支持使用 FastAPI?如果没有,有没有办法监听
快速API 0.68.0 python 3.8 from fastapi import Depends, FastAPI, Header, HTTPException async def verify
在 FastAPI 框架内: 虽然请求数据当然可以作为参数传递,但我想知道函数是否可以在不传递参数的情况下访问有关当前请求的信息。 免责声明:我不认为全局访问请求数据是一个好的做法,但我有一个用例,如
无论如何,FastAPI“依赖项”是否可以解释路径参数。 我有很多形式的功能: @app.post("/item/{item_id}/process", response_class=ProcessR
我有一个由诗歌构建的 fastapi 项目。我想使用 pyproject.tom 中的脚本部分运行应用程序,如下所示: poetry run start 该部分的双引号内是什么? [tool.poet
我正在尝试将分页添加到我的 fastapi 项目中。所以我决定使用这个: fastapi-contrib 我在那里遵循相同的示例,但由于某种原因我收到此错误: type object 'MOrdene
在我的项目文件夹中,我有一个基本的 index.html文件加上静态文件(js、css)以及我的 main.py : from fastapi.staticfiles import StaticFil
FastAPI显示可以设置response_model_exclude_none=True在装饰器中忽略值为 None 的字段:https://fastapi.tiangolo.com/tutoria
FastAPI 生成自动 swagger/openapi 文档。 在 https://fastapi.tiangolo.com/tutorial/response-status-code 的教程中有一
我获得了使用FastApi运行推理服务器的以下代码。在大约8小时内,我的RAM内存增加了4Gi。。更有趣的是,当我停止我的容器时,内存并没有清理干净。。例如,在运行Docker Container之前
今天的文章分享如下在 FastAPI 框架下,使用 pytest 来自动化测试数据库相关的接口,文章的最后给出全部代码。 最近越来越喜欢使用 FastAPI 来写后端服务了,因为它是 Pyth
Docker 学习 https://www.cnblogs.com/poloyy/p/15257059.html 项目结构 .├── app│ ├── __init__.py│ └
下面代码来自官方FastAPI tutorials page ,我无法理解这些语句(例如,name: str)。 from typing import Optional from fastapi im
我是网络通信的新手。我使用 ubuntu 并尝试学习 fastapi。但是,我认为很难理解如何格式化我打算发送回客户端的响应。 要发回的响应的规则是什么?如果您想发回自定义答案 - 例如两个图像文件
我正在尝试从文件中添加路由,但我事先并不知道实际的参数,因此我需要一个通用函数来通过 **kwargs 处理参数。 要添加路由,我正在使用 add_api_route,如下所示: from fasta
我按照此文档设置了一个用户: https://fastapi.tiangolo.com/advanced/security/http-basic-auth/ 但我只收到一个端点“/users/me”的
当我尝试从我的 postgre 数据库中获取一些数据并使用 fastapi 时出现此错误。 我不知道为什么会这样......但这是我的代码,谢谢你的帮助。 路线 @router.get("/fuent
我有一个与在 pycharm 中使用 uvicorn 的 FastAPI 有关的问题。我的项目具有以下结构: LearningPy | |-- apis -----|--modelser
我已经创建了一个登录路径,我在其中发布了我的表单数据并设置了一个 cookie。设置 cookie 后,我重定向到“/main”,在那里我得到 {detail:"Method Not Allowed"
当我使用 FastAPI 时,如何为网络服务指定基本路径? 换句话说 - FastAPI 对象是否有参数可以将端点和我定义的任何其他对象设置为不同的根路径? 例如,如果我的代码带有下面的虚假参数 ro
我是一名优秀的程序员,十分优秀!