I'm wondering if the nested "try/except/else" structure (in the main function) is a good practice in Python. Right now, the structure is not that deep but I could continue on and on with additional conditions in the "else" part. Is there a better way to implement this ?
My code written in main.py
:
import logging
import traceback
import flask
from google.cloud import firestore
class DocumentDoesNotExist(Exception):
"""
Exception raised when there is no document corresponding to a given token in Firestore/collectionA nor
Firestore/collectionB.
"""
class DocumentExistElsewhere(Exception):
"""
Exception raised when there is no document corresponding to a given token in Firestore/collectionA but there is
one in Firestore/collectionB.
"""
def get_patient_info(token):
db = firestore.Client()
document = db.collection(u'collectionA').document(token).get()
if document.exists:
return document.to_dict()
else:
document = db.collection(u'collectionB').document(token).get()
if document.exists:
raise DocumentExistElsewhere
else:
raise DocumentDoesNotExist
app = flask.Flask(__name__)
@app.route("/<request>")
def main(request: flask.Request):
headers = {
'Access-Control-Allow-Methods': 'OPTIONS, GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '9600'
}
allowed_origins = [
"http://localhost:5000"
]
origin = flask.request.headers.get('Origin') or flask.request.headers.get('origin')
if origin in allowed_origins:
headers['Access-Control-Allow-Origin'] = origin
if flask.request.method == 'OPTIONS':
return '', 204, headers
if flask.request.method == 'GET':
try:
request_json = flask.request.get_json(force=True, silent=True) # Returns None if fails.
token = request_json['token']
except (TypeError, KeyError):
logging.error(traceback.format_exc())
return "Cannot retrieve token from request", 400, headers
else:
try:
info = get_patient_info(token)
except DocumentDoesNotExist:
return "Token provided does not correspond to any document in Firestore/collectionA nor in " \
"collectionB.", 404, headers
except DocumentExistElsewhere:
return "Token provided corresponds to a document in Firestore/collectionB but none in " \
"Firestore/collectionA.", 404, headers
else:
return info, 200, headers
if __name__ == "__main__":
app.run(debug=True)
You can run the Flask app like this python3 main.py
and then testing with a curl curl -H "Origin: http://localhost:5000" -X GET -d '{"token":"06sr1"}' -i http://localhost:5000/test
Also, if you can see any problem with my implementation I'm open to any tips :)