【问题标题】:How to implement caching with WSGI?如何使用 WSGI 实现缓存?
【发布时间】:2014-05-24 05:37:01
【问题描述】:

我想构建一个缓存代理作为 Python WSGI 中间件,想知道这个中间件如何找出缓存页面是否过期。据我所知,WSGI 不支持 Java Servlets 的 getLastModified(HttpServletRequest req) 方法。

我不寻找的是带有“如果修改后”或“etags”的每个客户端缓存策略。我想为所有客户端(如代理服务器)缓存内容。因此缓存必须检查 WSGI 应用程序或 REST 方面的资源是否被修改并因此在缓存中过期。

 client               cache               wsgi app
 ------               -----               --------
    |   get /some/x     |                    |
    |------------------>| /some/x expired?   |
    |                   |------------------->|
    |                   |                    |
    |                   | update /some/x     |
    |                   | if modified        |
    | return /some/x    |<-------------------|
    |<------------------| 

不绕过WSGI可以实现吗?

【问题讨论】:

    标签: python caching proxy wsgi


    【解决方案1】:

    当然可以。首先,只有您知道资源是否过期,资源可能来自文件,可能来自数据库的文章,因此,不会有适用于您的全域“是否过期”方法。这是一个简单的例子:

    class WSGICache(object):
    
        def __init__(self, app):
            self.app = app
            self.cache = {}
    
        def is_expired(self, environ):
            """Determine is the resource the request for already expired?
    
            """
            # FIXME: check is the resource expired, by looking
            # PATH_INFO, if it is a file, it might be last modified time
            # if it is an object from database, see what is the last modified time
            return False
    
        def __call__(self, environ, start_response):
            path = environ['PATH_INFO']
            cached = self.cache.get(path)
            # do we have valid cache?
            if self.is_expired(environ) or not cached:
                cached = list(self.app(environ, start_response))
                self.cache[path] = cached
            return cached
    

    但对于生产用途,我建议使用一些已经构建的缓存系统,例如Beaker,我认为它应该足以满足您的需求。 我没有测试上面的代码,但是像这样的中间件可以做你想做的事。

    【讨论】:

      【解决方案2】:

      当您说“构建”时,您的意思是自己配置或开发一个。问题是那里有大量的 HTTP 缓存工具。我建议你看看:

      1. Optimising Web Delivery
      2. mod_cache in Apache

      使用此工具,您可以配置超时以刷新缓存。我猜的问题是你的内容有多动态。如果您的内容是相当静态的,那么这些工具中的任何一个都应该适用于这种情况。

      对于这里的 WSGI,你有一个配置 example with SQUID Cache

      【讨论】:

        【解决方案3】:

        您可以尝试搁置https://docs.python.org/2/library/shelve.html

        如果你想用它来缓存网页,你可以将网页代码存储在搁置或缓存中,然后将其返回给客户端,并在需要时让 wsgi 修改页面。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-15
          • 1970-01-01
          • 2012-10-25
          • 1970-01-01
          相关资源
          最近更新 更多