Created
June 21, 2022 09:18
-
-
Save jcarlosroldan/4e022f04ed5dad2301b66ec559212e52 to your computer and use it in GitHub Desktop.
Minimal Flask server for a JSON API
This file contains hidden or 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
from flask import Flask | |
from flask.helpers import request | |
from traceback import format_exc | |
SERVER = Flask(__name__) | |
PORT = 5000 | |
# SSL_CONTEXT = '/etc/ssl/certificate.crt', '/etc/ssl/private.key' | |
SSL_CONTEXT = None | |
def api(data: dict): | |
return {'foo': 'bar'} # TODO | |
@SERVER.route('/', defaults={'path': ''}, methods=['GET', 'POST']) | |
@SERVER.route('/<path:path>', methods=['GET', 'POST']) | |
def catch_all(path: str): | |
json_data = request.get_json() | |
if 'X-Forwarded-For' in request.headers: | |
ip = request.headers['X-Forwarded-For'] | |
else: | |
ip = request.remote_addr | |
data = { | |
**request.headers, | |
**request.cookies, | |
**request.files, | |
**request.values, | |
**({} if json_data is None else json_data), | |
'ip': ip, | |
'endpoint': path[4:] if path.startswith('api/') else path | |
} | |
try: | |
res = api(data), 200 | |
except: | |
res = { | |
'error': 'unknownError', | |
'parameters': format_exc().strip().split('\n') | |
}, 500 | |
return res | |
SERVER.run(host='0.0.0.0', port=PORT, debug=True, ssl_context=SSL_CONTEXT) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment