6

memcached を使用して Python/フラスコの応答をキャッシュしようとしています。次に、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

つまり、データのみをキャッシュする必要があり、最初に make_response を実行した場合にのみ実行できます。

于 2012-04-07T13:59:40.530 に答える