Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_build_error(self):
err = HttpError("Whoopsie")
resp = self.res.build_error(err)
resp_body = json.loads(resp.body)
self.assertEqual(resp_body, {'error': 'Whoopsie'})
self.assertEqual(resp.content_type, 'application/json')
self.assertEqual(resp.status_code, 500)
nf_err = NotFound()
resp = self.res.build_error(nf_err)
resp_body = json.loads(resp.body)
# Default error message.
self.assertEqual(resp_body, {'error': 'Resource not found.'})
self.assertEqual(resp.content_type, 'application/json')
# Custom status code.
self.assertEqual(resp.status_code, 404)
# Non-restless exception.
unknown_err = AttributeError("'something' not found on the object.")
resp = self.res.build_error(unknown_err)
resp_body = json.loads(resp.body)
# Still gets the JSON treatment & an appropriate status code.
self.assertEqual(resp_body, {'error': "'something' not found on the object."})
self.assertEqual(resp.content_type, 'application/json')
self.assertEqual(resp.status_code, 500)
"""
understood = (
KeyError, ValueError, TypeError, AttributeError,
SQLAlchemyError, DokomoError
)
if isinstance(err, tornado.web.HTTPError):
restless_error = exc.HttpError(err.log_message)
restless_error.status = err.status_code
err = restless_error
elif isinstance(err, SurveyAccessForbidden):
restless_error = exc.HttpError(str(err))
restless_error.status = 403
err = restless_error
elif isinstance(err, NoResultFound):
err = exc.NotFound()
elif isinstance(err, understood):
err = exc.BadRequest(err)
logging.exception(err)
return super().handle_error(err)
def build_error(self, err):
# A bit nicer behavior surrounding things that don't exist.
if isinstance(err, (ObjectDoesNotExist, Http404)):
err = NotFound(msg=six.text_type(err))
return super(DjangoResource, self).build_error(err)
:param pk: ID of record
Example:
food = Food.get_or_404(1)
food.name
>>> Palmito
food.price
>>> 10.9
"""
obj = cls.query.get(pk)
if obj:
return obj
else:
raise NotFound()
food.name
>>> CuzCuz
# not found
food = get_or_404(Food, 42)
# { "error": "Food not found" }
"""
if bind:
obj = session.using(bind).query(_model).get(id)
else:
obj = session.query(_model).get(id)
if obj:
return obj
else:
raise NotFound('{0} not found'.format(_model.__name__))