首页 > 解决方案 > 烧瓶如何保存 SQLAlchemyobject 的实例

问题描述

我想为任何模板加载一个全局菜单。查询的结构总是相同的......

class ProductCats(db.Model):
   def __init__(self,
              lang=None,
              catname=None,
              catid=None,
              update=False,
              active=False,
              create=False,
              ):

              self.categories = db.session.query(ProductCats, ProductCatsTranslations)
              if lang:
                  self.categories = self.categories.filter(ProductCatsTranslations.language_code==lang)
   
              if catid:
                  self.categories = self.categories.filter(ProductCatsTranslations.catid==catid)
   
              if active:
                  self.categories = self.categories.filter(ProductCats.active==active)
                                                                                                                                                                                           
   
              self.categories = self.categories.filter(ProductCatsTranslations.catid==ProductCats.catid).\
              order_by(ProductCatsTranslations.sort)
   

              self.dicted_by_catid = {}
   
              for c, ct in self.categories:
                  c.ct = ct
                  self.dicted_by_catid[c.catid] = c 

     # then I have a method within this class
     def by_catid(self, catid=None):
          return self.dicted_by_catid[catid]

在我的烧瓶应用程序的init .py 中

@app.before_request
def before_request():
    from models import ProductCats
    g.productcats = ProductCats(lang=lang)

所以我可以在flaskapp 的任何地方轻松访问我的productcats。但它每次都会启动一个查询,而不是从字典“by_catid”中获取它。我叫这样的东西。例如,在模板中或视图中或此应用程序中的任何位置。

g.productcats.by_catid(catid=12).name
g.productcats.by_catid(catid=172).name

这会从ProductCats的init中产生两个查询而不是一个

当我在我的应用程序的其他地方(例如在我的主页视图上)手动设置 ProductCats() 的init的相同 db.query 时,我可以随时调用该属性,而无需每次都创建新的查询。

好像有什么特别的,那个 g.object 每次都在调用 ProductCats 的 init 方法?但是当我在我的 ProductCats 初始化中添加一个简单的调试输出时,它只出现一次。与 ProductCatsTranslation 的关系也是惰性连接的。当不使用flask-global(g)时,它也可以在我的homeview中使用。

如果我仍然可以在我的模板中使用我的 Productcats 实例,我如何在不为每个类别生成一个查询的情况下在整个应用程序中拥有我的 productcats,例如

g.productcats.by_catid(catid=12).name
g.productcats.by_catid(catid=14).otherattribute
g.productcats.by_catid(catid=12).active

标签: pythonflasksqlalchemyglobal-variablesinstance

解决方案


推荐阅读