2009-03-31
encode("zlib")でwsgiアプリをdeflate対応させる
strのメソッドencode()やdecode()では、"utf-8"などの文字コードだけじゃなく"base64"、"zlib"、"bz2"、"uu"、"hex"、"rot13"といったものもつかえるようです(/usr/lib/python2.6/encodings/以下にある)。でもなぜか"gzip"はありません。
encode("zlib")をつかって以下のようにすることで、wsgiアプリをdeflate対応にできます。
#!/usr/bin/env python # -*- coding: utf-8 mode: python -*- def application(env, start_response): status = "200 OK" headers = [("Content-Type", "text/html;charset=UTF-8")] deflate = "deflate" in env.get("HTTP_ACCEPT_ENCODING", "").split(",") content = "<html><body>" content += "Hello %s" % ("deflate" if deflate else "identity") content += "</body></html>" if deflate: headers.append(("Content-Encoding", "deflate")) content = content.encode("zlib") pass start_response(status, headers) return [content] if __name__ == "__main__": from wsgiref.handlers import CGIHandler CGIHandler().run(application) pass
decoratorにもできますね
def deflatable(app): def deflator(env, start_res): deflate = "deflate" in env.get("HTTP_ACCEPT_ENCODING", "").split(",") def start_wrapper(status, headers): headers.append(("Content-Encoding", "deflate")) return start_res(status, headers) contents = app(env, start_wrapper if deflate else start_res) return ["".join(contents).encode("zlib")] if deflate else contents return deflator @deflatable def application(env, start_response): ...
トラックバック - http://d.hatena.ne.jp/bellbind/20090331/1238517927
リンク元
- 7 http://www.google.co.jp/search?hl=ja&client=firefox-a&rls=org.mozilla:ja:official&hs=TJF&q=python+deflate&btnG=検索&lr=lang_ja
- 6 http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=Python+Deflate
- 5 http://www.google.co.jp/search?q=python+deflate&lr=lang_ja&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:ja:official&client=firefox-a
- 4 http://reader.livedoor.com/reader/
- 4 http://www.google.co.jp/reader/view/
- 4 http://www.google.co.jp/search?sourceid=navclient&hl=ja&ie=UTF-8&rlz=1T4GGIH_jaJP235JP235&q=content-type+deflate
- 4 http://www.google.co.jp/url?sa=t&rct=j&q=python deflate&source=web&cd=1&ved=0CCkQFjAA&url=http://d.hatena.ne.jp/bellbind/20090331/1238517927&ctbs=lr:lang_1ja&ei=1qCzTsS6Ca2ImQWy19XAAw&usg=AFQjCNH0XvR9oynH1-vfMVRtURd0si_-VQ&cad=rja
- 3 http://www.google.co.jp/search?q=Python+Deflate&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a
- 2 http://d.hatena.ne.jp/
- 2 http://ezsch.ezweb.ne.jp/search/?sr=0101&query=deflate body