默认CACHE_TYPE
是null
给你一个NullCache
- 所以你根本没有缓存,这是你观察到的。该文档没有明确说明这一点,但源代码中的这一行Cache.init_app
确实:
self.config.setdefault('CACHE_TYPE', 'null')
要实际使用一些缓存,请初始化您的Cache
实例以使用适当的缓存。
cache = Cache(config={'CACHE_TYPE': 'simple'})
旁白:请注意,这SimpleCache
对于开发和测试以及此示例非常有用,但您不应该在生产中使用它。类似MemCached
或RedisCache
会更好的东西
现在,有了实际的缓存,您将遇到下一个问题。在第二次调用时,lxml.html
将从 中检索缓存的对象Cache
,但由于这些对象不可缓存,因此已损坏。Stacktrace 看起来像这样:
Traceback (most recent call last):
File "/home/day/.virtualenvs/so-flask/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/home/day/.virtualenvs/so-flask/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/home/day/.virtualenvs/so-flask/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/home/day/.virtualenvs/so-flask/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/day/.virtualenvs/so-flask/lib/python2.7/site-packages/flask/app.py", line 1358, in full_dispatch_request
rv = self.dispatch_request()
File "/home/day/.virtualenvs/so-flask/lib/python2.7/site-packages/flask/app.py", line 1344, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/home/day/q12030403.py", line 20, in index
return "get_content returned: {0!r}\n".format(get_content())
File "lxml.etree.pyx", line 1034, in lxml.etree._Element.__repr__ (src/lxml/lxml.etree.c:41389)
File "lxml.etree.pyx", line 881, in lxml.etree._Element.tag.__get__ (src/lxml/lxml.etree.c:39979)
File "apihelpers.pxi", line 15, in lxml.etree._assertValidNode (src/lxml/lxml.etree.c:12306)
AssertionError: invalid Element proxy at 3056741852
因此lxml.html
,您不应该缓存对象,而应该只缓存简单的字符串——您下载的网站的内容,然后重新解析它以lxml.html
每次都获得一个新的对象。您的缓存仍然有帮助,因为您不会每次都访问其他网站。这是一个完整的程序来演示有效的解决方案:
from flask import Flask
from flask.ext.cache import Cache
import time
import lxml.html
import urllib2
app = Flask(__name__)
cache = Cache(config={'CACHE_TYPE': 'simple'})
cache.init_app(app)
@cache.cached(timeout=86400, key_prefix='content')
def get_content():
app.logger.debug("get_content called")
# return lxml.html.fromstring(urllib2.urlopen('http://daybarr.com/wishlist').read())
return urllib2.urlopen('http://daybarr.com/wishlist').read()
@app.route("/")
def index():
app.logger.debug("index called")
return "get_content returned: {0!r}\n".format(get_content())
if __name__ == "__main__":
app.run(debug=True)
当我运行程序并向 发出两个请求时http://127.0.0.1:5000/
,我得到了这个输出。请注意,这get_content
不是第二次调用,因为内容是从缓存中提供的。
* Running on http://127.0.0.1:5000/
* Restarting with reloader
--------------------------------------------------------------------------------
DEBUG in q12030403 [q12030403.py:20]:
index called
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
DEBUG in q12030403 [q12030403.py:14]:
get_content called
--------------------------------------------------------------------------------
127.0.0.1 - - [21/Dec/2012 00:03:28] "GET / HTTP/1.1" 200 -
--------------------------------------------------------------------------------
DEBUG in q12030403 [q12030403.py:20]:
index called
--------------------------------------------------------------------------------
127.0.0.1 - - [21/Dec/2012 00:03:33] "GET / HTTP/1.1" 200 -