我正在尝试使用 memcached 缓存 Python/flask 响应。然后我想使用 nginx 提供缓存。我正在使用看起来像这样的烧瓶代码:
from flask import Flask, render_template
from werkzeug.contrib.cache import MemcachedCache
app = Flask(__name__)
cache = MemcachedCache(['127.0.0.1:11211'])
@app.route('/')
def index():
index = cache.get('request:/')
if index == None:
index = render_template('index.html')
cache.set('request:/', index, timeout=5 * 60)
return index
if __name__ == "__main__":
app.run()
和一个看起来像这样的 nginx 站点配置:
server {
listen 80;
location / {
set $memcached_key "request:$request_uri";
memcached_pass 127.0.0.1:11211;
error_page 404 405 502 = @cache_miss;
}
location @cache_miss {
uwsgi_pass unix:///tmp/uwsgi.sock;
include uwsgi_params;
error_page 404 /404.html;
}
}
但是,当它从缓存中提取时,html 代码以 V 为前缀,包含 \u000a 字符(换行符)和乱码的本地字符,并以“p1”为后缀。像这样:
V<!doctype html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\u000a<head>\u000a <meta http-equiv="content-type" content="text/html; charset=UTF-8" />\u000a <meta http-equiv="content-language" content="no">\u000a\u000a <title>
[...]
\u000a\u000a</body>\u000a</html>
p1
.
尽管 Content-Type 是“text/html; charset=utf-8”。据说 V [...] p1 。事情可能与分块传输编码有关,这是响应标头中不存在的标志。我该怎么办?