带有烧瓶和memcached的nginx返回一些乱码

时间:2012-04-04 17:44:09

标签: python caching nginx memcached flask

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

1 个答案:

答案 0 :(得分:4)

是的,我修好了!在更改chunked之前,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

也就是说,我只应该缓存数据,而且只有在我首先做make_response时才能完成,但是这样才能完成