理解会话与fastApi的依赖关系



我是Python新手,正在学习FastApi和SQL模型。

参考链接:https://sqlmodel.tiangolo.com/tutorial/fastapi/session-with-dependency/#the-with-block

这里,他们有这样的东西

def create_hero(*, session: Session = Depends(get_session), hero: HeroCreate):
db_hero = Hero.from_orm(hero)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
return db_hero

这里我无法理解这部分

session.add(db_hero)
session.commit()
session.refresh(db_hero)

它在做什么,它是如何工作的?

不能理解这个

In fact, you could think that all that block of code inside of the create_hero() function is still inside a with block for the session, because this is more or less what's happening behind the scenes.
But now, the with block is not explicitly in the function, but in the dependency above:

这是文档中关于session的解释

在最一般的意义上,会话建立所有的会话和表示所有对象的"保持区"在它的生命周期中你已经加载或与之关联的。它提供了执行SELECT和其他查询的接口将返回并修改orm映射的对象。ORM对象本身在Session中维护,在一个叫做身份映射——一种维护每个副本的唯一副本的数据结构对象,其中"唯一"是指"只有一个对象具有特定的主键"。

# This line just simply create a python object
# that sqlalchemy would "understand".
db_hero = Hero.from_orm(hero)
# This line add the object `db_hero` to a “holding zone”
session.add(db_hero)
# This line take all objects from a “holding zone” and put them in a database
# In our case we have only one object in this zone, 
# but it is possible to have several
session.commit()
# This line gets created row from the database and put it to the object. 
# It means it could have new attributes. For example id, 
# that database would set for this new row
session.refresh(db_hero)

最新更新