def json_api_handler(handler):
"""Bottle handler decorator for JSON REST API handlers.
Args:
handler: A Bottle handler function.
Returns:
A wrapped Bottle handler function.
"""
@functools.wraps(handler)
def wrapped_handler(*args, **kwargs):
try:
handler_result = handler(*args, **kwargs)
except bottle.HTTPResponse as handler_result:
pass
except Exception:
logging.exception('Uncaught exception')
handler_result = bottle.HTTPError(500, 'Internal Server Error')
if isinstance(handler_result, bottle.HTTPResponse):
# For now, we do not support raising successful HTTPResponse.
assert handler_result.status_code // 100 != 2
# Forcibly convert HTTPError to HTTPResponse to avoid formatting.
response = handler_result.copy(cls=bottle.HTTPResponse)
response_data = {'ok': False, 'error': handler_result.body}
else:
assert isinstance(handler_result, dict)
response = bottle.response.copy(cls=bottle.HTTPResponse)
response_data = handler_result
response_data['ok'] = True
response.body = ujson.dumps(response_data, double_precision=6)
response.content_type = 'application/json'
return response
return wrapped_handler
评论列表
文章目录