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

jon*_*doe 6 python memcached caching nginx 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()
Run Code Online (Sandbox Code Playgroud)

和一个看起来像这样的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,当它从缓存中拉出时,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
.
Run Code Online (Sandbox Code Playgroud)

尽管Content-Type是"text/html; charset = utf-8".据说是V [...] p1.事情可能与chunked传输编码有关,某个标志在响应头中不存在.我该怎么办?

jon*_*doe 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
Run Code Online (Sandbox Code Playgroud)

也就是说,我应该只缓存数据,而且这只能完成,据我所知,如果我先执行 make_response