2017-05-02 04:23:16 +00:00
|
|
|
import flask
|
|
|
|
from flask import request
|
|
|
|
import functools
|
|
|
|
|
2018-01-10 05:21:15 +00:00
|
|
|
import etiquette
|
|
|
|
|
2017-12-16 20:25:01 +00:00
|
|
|
from . import jsonify
|
2017-05-02 04:23:16 +00:00
|
|
|
|
2018-01-10 05:21:15 +00:00
|
|
|
def catch_etiquette_exception(function):
|
|
|
|
'''
|
|
|
|
If an EtiquetteException is raised, automatically catch it and convert it
|
2018-09-23 21:57:25 +00:00
|
|
|
into a json response so that the user isn't receiving error 500.
|
2018-01-10 05:21:15 +00:00
|
|
|
'''
|
|
|
|
@functools.wraps(function)
|
|
|
|
def wrapped(*args, **kwargs):
|
|
|
|
try:
|
|
|
|
return function(*args, **kwargs)
|
2020-09-19 10:08:45 +00:00
|
|
|
except etiquette.exceptions.EtiquetteException as exc:
|
|
|
|
if isinstance(exc, etiquette.exceptions.NoSuch):
|
2018-01-10 05:21:15 +00:00
|
|
|
status = 404
|
|
|
|
else:
|
|
|
|
status = 400
|
2021-01-01 20:56:05 +00:00
|
|
|
response = exc.jsonify()
|
2018-01-10 05:21:15 +00:00
|
|
|
response = jsonify.make_json_response(response, status=status)
|
|
|
|
flask.abort(response)
|
|
|
|
return wrapped
|
|
|
|
|
2017-05-02 04:23:16 +00:00
|
|
|
def required_fields(fields, forbid_whitespace=False):
|
|
|
|
'''
|
|
|
|
Declare that the endpoint requires certain POST body fields. Without them,
|
|
|
|
we respond with 400 and a message.
|
|
|
|
|
|
|
|
forbid_whitespace:
|
|
|
|
If True, then providing the field is not good enough. It must also
|
|
|
|
contain at least some non-whitespace characters.
|
|
|
|
'''
|
|
|
|
def wrapper(function):
|
|
|
|
@functools.wraps(function)
|
|
|
|
def wrapped(*args, **kwargs):
|
|
|
|
for requirement in fields:
|
|
|
|
missing = (
|
|
|
|
requirement not in request.form or
|
|
|
|
(forbid_whitespace and request.form[requirement].strip() == '')
|
|
|
|
)
|
|
|
|
if missing:
|
|
|
|
response = {
|
|
|
|
'error_type': 'MISSING_FIELDS',
|
|
|
|
'error_message': 'Required fields: %s' % ', '.join(fields),
|
|
|
|
}
|
|
|
|
response = jsonify.make_json_response(response, status=400)
|
|
|
|
return response
|
|
|
|
|
|
|
|
return function(*args, **kwargs)
|
|
|
|
return wrapped
|
|
|
|
return wrapper
|