python - 烧瓶如何保存 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
解决方案
推荐阅读
- php - Chrome 忽略 Content-Disposition 文件名
- r - 如何按因子计算变量?
- python - 熊猫中的if语句-python
- excel - 在 VBA 范围比较中查找行值
- ubuntu - 如何在 ubuntu 上重新启动 nginx Web 服务器而不会出错?
- reactjs - 有没有办法让整个页面在单击按钮之前不可编辑?
- mongodb - 查找特定用户 mongodb 最喜欢的产品
- html - 如何在点击时隐藏垂直导航并显示相应的内容(移动网站上的导航带有后退按钮)
- swift - 应用程序快速显示具有不同字符的文本
- ruby - 在 rub 中获取特定主机的 IP 地址