2012-04-04 47 views
6

我試圖用memcached緩存Python/flask響應。然後我想用nginx來提供緩存。我使用燒瓶代碼看起來是這樣的:帶燒瓶和memcached的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。事情可能與分塊傳輸編碼有關,標記不存在於響應頭中。我該怎麼辦?

+0

好吧,所以我半固定它。它,我添加了add_header Transfer-Encoding chunked;在nginx配置中,但現在我得到'錯誤321(net :: ERR_INVALID_CHUNKED_ENCODING)',如果我已經加載它在Firefox中加載它後。也許有更好的方法來做這種類型的cachine? – jondoe 2012-04-04 18:51:30

回答

4

耶,我修好了! nginx的配置是正確的之前,我改變分塊,蟒蛇/瓶代碼然而本來應該:

@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第一個