Refactoring /result and making errors more explicit

This commit is contained in:
Denis-Cosmin Nutiu 2017-04-23 22:46:39 +03:00
parent 0513695586
commit 5265ff8e14

View file

@ -45,36 +45,35 @@ def result_post():
""" """
Allows the upload of resources via POST. Allows the upload of resources via POST.
""" """
content = flask.request.get_json()
error = None
gpu = cpu = log = score = name = None
try: try:
content = flask.request.get_json()
name = content['name'] name = content['name']
gpu = content['gpu'] gpu = content['gpu']
cpu = content['cpu'] cpu = content['cpu']
log = content['log'] log = content['log']
score = int(content['score']) score = int(content['score'])
if score <= 0: if score <= 0:
error = "Score must be positive!" raise ValueError("Score must be positive!")
except KeyError: # Json doesn't contain the keys we need. except KeyError as e: # Json doesn't contain the keys we need.
error = "Invalid json keys: gpu, cpu, log, score name!" error = "Key not found: {}.".format(str(e))
except TypeError: # The types from the json object are not correct. except TypeError as e: # If we don't get a string
error = "Invalid json object!" error = str(e)
except ValueError as e:
error = str(e)
else:
# Add data to the database
entry = Result(name=name, gpu=gpu, cpu=cpu, log=log, score=score)
db.session.add(entry)
db.session.commit()
if error: flask.current_app.logger.info("{} added result with id: {}.".format(flask.request.remote_addr, entry.id))
return flask.jsonify({'error': error, 'success': False}), 400
# Add data to the database location = "/result/{}".format(entry.id)
entry = Result(name=name, gpu=gpu, cpu=cpu, log=log, score=score)
db.session.add(entry)
db.session.commit()
flask.current_app.logger.info("{} added result with id: {}.".format(flask.request.remote_addr, entry.id)) return flask.jsonify({'success': True}), 201, {'location': location}
# Exception occurred
location = "/result/{}".format(entry.id) return flask.jsonify({'error': error, 'success': False}), 400
return flask.jsonify({'success': True}), 201, {'location': location}
@utilities.cache.cached(timeout=60*5) @utilities.cache.cached(timeout=60*5)