6

我正在尝试使用 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 。事情可能与分块传输编码有关,这是响应标头中不存在的标志。我该怎么办?

4

1 回答 1

4

耶,我修好了!在我更改分块之前,nginx 配置是正确的,但是 python/flask 代码应该是:

@app.route('/')
def index():
    rv = cache.get('request:/')
    if rv == None:
        rv = render_template('index.html')
        cachable = make_response(rv).data
        cache.set('request:/', cachable, timeout=5 * 60)
    return rv

也就是说,我应该只缓存数据,而且只能这样做,afaik,如果我先做 make_response

于 2012-04-07T13:59:40.530 回答