【问题标题】:nginx with flask and memcached returns some garbled characters带有烧瓶和memcached的nginx返回一些乱码
【发布时间】:2012-04-18 11:29:13
【问题描述】:

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

【问题讨论】:

  • 好的,所以我把它修好了。它,我添加了 add_header Transfer-Encoding 分块;在 nginx 配置中,但现在我得到 Error 321 (net::ERR_INVALID_CHUNKED_ENCODING) 如果我在 Firefox 中加载它之后在 Chrome 中加载它。有没有更好的方法来做这种类型的机器?

标签: python caching nginx memcached flask


【解决方案1】:

是的,我修好了!在我更改分块之前,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 的情况下才能做到这一点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-28
    • 2016-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2021-01-28
    • 2012-10-30
    相关资源
    最近更新 更多