Archive
pretty JSON output with Flask-RESTful
Problem
Flask-RESTful is an awesome way to write REST APIs. In debug mode, its output is nicely indented, easy to read. However, in production mode the JSON is compressed and hard to read.
If debug is False, how to have a nicely formatted output?
Solution
from flask import Flask
from flask_restful import Api
app = Flask(__name__)
api = Api(app)
if production:
print("# running in production mode")
HOST = '0.0.0.0'
DEBUG = False
# START: temporary help for the UI developers, remove later
settings = app.config.get('RESTFUL_JSON', {})
settings.setdefault('indent', 2)
settings.setdefault('sort_keys', True)
app.config['RESTFUL_JSON'] = settings
# END
else:
print("# running in development mode")
HOST='127.0.0.1'
DEBUG = True
# ...
if __name__ == '__main__':
app.run(debug=DEBUG, host=HOST, port=1234)
Note that here I use the development server shipped with Flask, which is not suitable for real production. So this solution is between development and production.
Pretty print an integer
Exercise: Take an integer and print it in a pretty way, i.e. use commas as thousands separators. Example: 1977 should be 1,977.
Solution:
#!/usr/bin/env python
def numberToPrettyString(n):
"""Converts a number to a nicely formatted string.
Example: 6874 => '6,874'."""
l = []
for i, c in enumerate(str(n)[::-1]):
if i%3==0 and i!=0:
l += ','
l += c
return "".join(l[::-1])
#
if __name__ == "__main__":
number = 6874
print numberToPrettyString(number) # '6,874'
The idea is simple. Consider the number 1977. Convert it to string ("1977") and reverse it ("7791"). Start processing it from left to right and after every third character add a comma: "7" -> "77" -> "779," (comma added) -> "779,1". Now reverse the string ("1,977"). Done.
Links
- http://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators-in-python-2-x (for some more possible solutions)
Update (20131125)
There is an easier way. You can do it with string formatting too:
>>> n = 1977
>>> "{:,}".format(n)
'1,977'
Thanks to Krisztián B. for the tip.
