2011-02-25 125 views
2

我想建立一个缓存代理作为Python WSGI中间件,并想知道这个中间件如何能够找出缓存页是否过期。据我所知,WSGI不支持类似于Java Servlets的getLastModified(HttpServletRequest req)方法。如何使用WSGI实现缓存?

我不想要的是每个客户端缓存策略与“如果修改自”或“etags”。我想缓存所有客户端的内容,例如代理服务器。因此,缓存必须检查WSGI应用程序或REST方面的资源是否已被修改,从而在缓存中过期。

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

是否有可能实现它,而不通过WSGI?

回答

3

当然可以。首先,只有你知道资源是否过期,资源可能来自文件,数据库中的文章,因此,不会有宇宙“过期或不”的方法。下面是一个简单的例子:

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,我认为它应该是足够好,你想要做什么。 我没有测试上面的代码,但是像这样的中间件能够做你想做的。

1

当你说'build'时,你的意思是自己配置或开发一个。事情就是那里有大量的HTTP缓存工具。我建议你看看:

  1. Optimising Web Delivery
  2. mod_cache in Apache

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

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