Sample code that returns json with flask --uokada's diary
I opened it for a while from the above entry, but I found an easy way when I looked at Stack Overflow, so I will introduce it. http - RFC 1123 Date Representation in Python? - Stack Overflow
from wsgiref.handlers import format_date_time
This format_date_time function is the point. If you pass a time stamp to this, it will be formatted and output in RFC1123 format.
The sample code looks like this.
#!/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)
Launch the script and check the headers returned by the application.
% 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 is properly output in RFC 1123 format.
I didn't notice this function at all because it wasn't listed in the Japanese translation. 20.4. wsgiref — WSGI Utility and Reference Implementation — Python 2.7ja1 documentation
Recommended Posts