LoginSignup
6
6

More than 5 years have passed since last update.

FlaskでLast-Modifiedを設定する最も簡単な方法

Posted at

flaskでjsonを返すサンプルコード - uokadaの日記

上のエントリからしばらく開いてしまったけどStack Overflowみてたら簡単な方法を見つけたので紹介する。
http - RFC 1123 Date Representation in Python? - Stack Overflow

from wsgiref.handlers import format_date_time

このformat_date_time関数がポイント。
これにタイムスタンプを渡せばRFC1123形式へフォーマットして出力してくれる。

サンプルコードはこんな感じ。

#!/usr/bin/env  python2.7
from flask import Flask, jsonify, after_this_request
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime


app = Flask(__name__)

@app.route('/name/<name>.json')
def hello_world(name):
    greet = "Hello %s from flask!" % name
    result = {
        "Result":{
        "Greeting": greet
        }
    }
    @after_this_request
    def d_header(response):
        """ add header

        Arguments:
        - `response`:
        """
        now = datetime.now()
        stamp = mktime(now.timetuple())
        response.headers['Last-Modified'] = \
            format_date_time(stamp)
        return response
    return jsonify(ResultSet=result)

if __name__ == '__main__':
    app.run(debug=True)

スクリプトを起動してアプリケーションが返すヘッダーを確認します。

% curl -I localhost:5000/name/uokada.json
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 91
Last-Modified: Thu, 28 Feb 2013 17:47:20 GMT
Server: Werkzeug/0.8.3 Python/2.7.1
Date: Thu, 28 Feb 2013 17:47:20 GMT

Last-ModifiedがちゃんとRFC 1123の形式で出力されてますね。

この関数、日本語訳されているドキュメントに載ってないので全然気づかなかった。
20.4. wsgiref — WSGI ユーティリティとリファレンス実装 — Python 2.7ja1 documentation

6
6
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
6
6