【问题标题】:Bottle -- Redirect output of SimpleTemplate to static fileBottle -- 将 SimpleTemplate 的输出重定向到静态文件
【发布时间】:2019-04-10 01:00:46
【问题描述】:

我想为我一直在开发的瓶子网站实现一个缓存系统。这个想法是一些路由需要更长的时间来渲染,所以,如果自生成 html 文件以来 sqlite 表尚未更新,我将返回它,如果有,我将从中检索行数据库并将其保存到文件并返回。

可能有人已经这样做了,因此任何将“.tpl”模板的输出重定向到“.html”文件的提示将不胜感激。

我查看了一些通用缓存库,但它们似乎通过在特定时间间隔刷新缓存来工作,而我想在数据库更改时刷新。

谢谢。

编辑:我使用 Apache 作为反向代理,cheroot 作为应用服务器。

【问题讨论】:

    标签: python bottle


    【解决方案1】:

    首先你需要一个缓存对象。 dict 是一个不错的选择。

    cachetpl = {}
    lastupdated = time.time()
    cache = Cache()
    

    然后创建一个类来处理你的字典中的东西:

    class Cache(object):
        def __init__(self):
            global lastupdated
            self.lastupdated = lastupdated
            global cachetpl
            self.cachetpl = cachetpl
    
        def keys(self):
            return self.cachetpl.keys()
    
        def lastupdate(self):
            return self.lastupdate
    
        def meta(self, clienthash, zipcode=None):
            return self.cachetpl[clienthash]
    

    然后您需要设置一个脉冲来检查更改,也许检查 SQL 存储的 lastupdated 列。

    @staticmethod
    def update():
        global cachetpl
        global lastupdated
        if not cachetpl:
            return None, None
        PSQL = ''' SELECT key, meta FROM schema.table WHERE lastupdated >= %s '''        
        changes = db.fetchall(PSQL, lastupdated)
        if changes:
            numchange = len(changes)
            for x in changes:
                cachetpl[x[0]] = x[1]
            lastupdated = time.time()
            return len(cachetpl), numchange
        else:
            lastupdated = nz.now()
            return None, None
    

    如何设置此脉冲取决于您。我使用一个名为scheduler 的python 库,并为我的应用程序使用gevent 进行异步。效果很棒。

    现在你只需给你的班级打电话Cache() 并提供你想要的任何数据。我的建议是,不要返回模板,而是先将其保存在数据库中,然后再返回。让路由调用在渲染之前检查缓存版本。然后,如果数据更改,您可以修改更新以在后台呈现页面,因此下一次调用缓存是新数据。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-21
      • 2016-08-09
      • 2013-10-11
      • 2023-03-19
      • 2014-03-31
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      相关资源
      最近更新 更多