Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用WSGI实现缓存?_Python_Caching_Proxy_Wsgi - Fatal编程技术网

Python 如何使用WSGI实现缓存?

Python 如何使用WSGI实现缓存?,python,caching,proxy,wsgi,Python,Caching,Proxy,Wsgi,我想构建一个缓存代理作为Python WSGI中间件,并想知道这个中间件如何发现缓存页面是否过期。据我所知,WSGI不支持类似Javaservlet的方法 我不想看到的是每客户端缓存策略,带有“if modified since”或“etags”。我想缓存所有客户端的内容,比如代理服务器。因此,缓存必须检查WSGI应用程序或REST资源是否在缓存中被修改并因此过期 client cache wsgi app ------

我想构建一个缓存代理作为Python WSGI中间件,并想知道这个中间件如何发现缓存页面是否过期。据我所知,WSGI不支持类似Javaservlet的方法

我不想看到的是每客户端缓存策略,带有“if modified since”或“etags”。我想缓存所有客户端的内容,比如代理服务器。因此,缓存必须检查WSGI应用程序或REST资源是否在缓存中被修改并因此过期

 client               cache               wsgi app
 ------               -----               --------
    |   get /some/x     |                    |
    |------------------>| /some/x expired?   |
    |                   |------------------->|
    |                   |                    |
    |                   | update /some/x     |
    |                   | if modified        |
    | return /some/x    |<-------------------|
    |<------------------| 
客户端缓存wsgi应用程序
------               -----               --------
|获取/部分/x||
|------------------>|/some/x过期了吗|
|                   |------------------->|
|                   |                    |
||更新/部分/x|
||如果修改|

|return/some/x |当你说“构建”时,你的意思是自己配置或开发一个。问题是有很多HTTP缓存工具。我建议您看看:

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


    对于WSGI,这里有一个配置,当然可以。首先,只有您知道资源是否过期,资源可能来自文件、数据库中的文章,因此,不会有一个通用的“过期或未过期”方法。下面是一个简单的例子:

    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
    
    但对于生产使用,我建议使用一些已经构建好的缓存系统,比如,我认为它应该足够好,可以满足您的需要。
    我没有测试上面的代码,但是像这样的中间件可以实现您想要的功能

    您可以尝试搁置

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