Last active
May 7, 2021 02:50
-
-
Save rfong/0b4138a221db8cb1a118f9fabc47a995 to your computer and use it in GitHub Desktop.
miscellaneous useful Flask things
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Flask application response handlers. | |
Reference: https://opensource.com/article/17/3/python-flask-exceptions | |
""" | |
from flask import Blueprint, jsonify | |
errors = Blueprint('errors', __name__) | |
class MyException(Exception): | |
pass | |
@errors.app_errorhandler(MyException) | |
def handle_generic_error(error): | |
"""App handler for expected server errors.""" | |
message = [str(x) for x in error.args] | |
status_code = 500 | |
success = False | |
response = { | |
'success': success, | |
'error': { | |
'type': error.__class__.__name__, | |
'message': message | |
} | |
} | |
return jsonify(response), status_code | |
@errors.app_errorhandler(Exception) | |
def handle_unexpected_error(error): # pylint: disable=unused-argument | |
"""App handler for unexpected errors.""" | |
status_code = 500 | |
success = False | |
response = { | |
'success': success, | |
'error': { | |
'type': 'UnexpectedException', | |
'message': 'An unexpected error has occurred.' | |
} | |
} | |
return jsonify(response), status_code |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
useful routing & view functionality for Flask app | |
""" | |
import os | |
import flask | |
from my_app_name.flask_app import app | |
@app.route('/docs/<path:subpath>') | |
def docs(subpath): | |
"""Reroute /docs to static files in generated doc subpath""" | |
if subpath == '' or subpath is None: | |
subpath = 'index.html' | |
return flask.send_from_directory( | |
os.path.join(app.static_folder, 'my_app_name'), subpath) | |
@app.route('/docs', strict_slashes=False) | |
def docs_root(): | |
"""Reroute to docs index""" | |
return docs('') | |
# Helpers | |
def dump_html_safe_db_list(db_obj_list): | |
"""Get an HTML safe string representation of a list of DB objects.""" | |
return ', '.join(get_html_safe_db_repr(o) for o in db_obj_list) | |
def get_html_safe_db_repr(db_obj): | |
"""Get an HTML safe string representation of a DB object.""" | |
return convert_html_brackets(repr(db_obj)) | |
def convert_html_brackets(s): | |
"""Convert repr <> brackets to HTML-plaintext-compatible [] brackets.""" | |
return s.replace('<', '[').replace('>', ']') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment