LoginSignup
12
14

More than 5 years have passed since last update.

FlaskでGzipに圧縮したCSSを送信

Last updated at Posted at 2014-05-10

bootstrap.min.css のロードが遅い問題を改善したくて、cssをgzipでどうすれば送信できるのか…と考えて調べた結果、無事出来たのでメモる。

Viewを作る

とりあえず、新しくViewを作りましょう。
今回は bootstrap.min.css をGzipで圧縮したものを送信するので、 /bootstrap.gz.css という名前でURIを作ります。

@app.route("/bootstrap.gz.css")

Gzip圧縮

次に、Gzip圧縮したCSSファイルを読み込みます。(おそらく、通常のCSSファイルを読み込んで gzip モジュールで圧縮しても大丈夫だと思います)

fp = open("static/css/bootstrap.min.css.gz")
content = fp.read()
fp.close()

ヘッダーにひとてま加える

このままではダメなので、ヘッダーに一手間加えましょう。今回はGZIPで圧縮しているので、 Content-Encoding ヘッダに情報を加えます。

res = make_response(content)
res.headers["Content-Type"] = "text/css"
res.headers["Content-Encoding"] = "gzip"

これらを一つにすると、以下のコードになります。
今回はCSSを圧縮したものを送信しましたが、Javascriptや画像でも同じ事ができると思います…!

@view.route("/bootstrap.gz.css")
def Bootstrap():
    fp = open("static/css/bootstrap.min.css.gz")
    content = fp.read()
    fp.close()

    res = make_response(content)
    res.headers["Content-Type"] = "text/css"
    res.headers["Content-Encoding"] = "gzip"

    return res

是非参考にしてください!

12
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
14