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_http_status_raised_from_error_handler(self):
mw = CaptureResponseMiddleware()
app = falcon.App(middleware=mw)
app.add_route('/', MiddlewareClassResource())
client = testing.TestClient(app)
def _http_error_handler(error, req, resp, params):
raise falcon.HTTPStatus(falcon.HTTP_201)
# NOTE(kgriffs): This will take precedence over the default
# handler for facon.HTTPError.
app.add_error_handler(falcon.HTTPError, _http_error_handler)
response = client.simulate_request(path='/', method='POST')
assert response.status == falcon.HTTP_201
assert mw.resp.status == response.status
def test_DocumentNotFound(self):
e = exceptions.DocumentNotFound(message='testing')
self.assertRaises(falcon.HTTPError,
e.handle, self.ex, self.mock_req, self.mock_req, None)
def on_post(req, resp):
"""
Create user. Currently used only in debug mode.
"""
data = load_json_body(req)
connection = db.connect()
cursor = connection.cursor()
try:
cursor.execute('INSERT INTO `user` (`name`) VALUES (%(name)s)', data)
connection.commit()
except db.IntegrityError:
raise HTTPError('422 Unprocessable Entity',
'IntegrityError',
'user name "%(name)s" already exists' % data)
finally:
cursor.close()
connection.close()
resp.status = HTTP_201
logger.error("Can't verify user")
raise falcon.HTTPBadRequest(title="Bad request",
description=e,
href=settings.__docs__)
try:
raw_json = req.stream.read()
logger.debug("Got incoming JSON data")
except Exception as e:
logger.error("Can't read incoming data stream")
raise falcon.HTTPBadRequest(title="Bad request",
description=e,
href=settings.__docs__)
try:
result_json = json.loads(raw_json.decode("utf-8"), encoding='utf-8')
except ValueError:
raise falcon.HTTPError(falcon.HTTP_400,
'Malformed JSON',
'Could not decode the request body. The '
'JSON was incorrect.')
try:
category = Category.get(Category.id == int(id))
if user not in category.allowed_users:
raise falcon.HTTPForbidden(title="Permission denied",
description="You don't have access to this resource",
href=settings.__docs__)
category.name = result_json["name"]
category.save()
res.status = falcon.HTTP_200
res.body = json.dumps({"message": "Category updated"})
except Exception as e:
print(e)
error_msg = ("Unable to get the category. Please try again later.")
def parse_payload(http_request):
try:
raw_payload_data = http_request.stream.read().decode('utf-8')
except Exception as ex:
logger.error("Bad request, reason unknown. Returning 400.")
raise falcon.HTTPError(falcon.HTTP_400, 'Error', ex.message)
try:
json_payload = json.loads(raw_payload_data)
except ValueError:
logger.error("Received invalid JSON: {:}".format(raw_payload_data))
logger.error("Returning 400 error.")
raise falcon.HTTPError(falcon.HTTP_400, 'Invalid JSON', 'Could not decode request body.')
return json_payload
def on_get(self, req, res):
raise falcon.HTTPError(falcon.HTTP_405,
title="Client error",
description=req.method + " method not allowed.",
href=settings.__docs__)
def on_update(self, req, res):
raise falcon.HTTPError(falcon.HTTP_405,
title="Client error",
description=req.method + " method not allowed.",
href=settings.__docs__)
"status": resp.status
}]
}
raise falcon.HTTPError(resp.status, title="Invalid client secret")
else:
resp.status = falcon.HTTP_UNAUTHORIZED
req.context["result"] = {
"errors":
[{
"id": "CLIENT_ID_INVALID",
"type": "error",
"text": "Couldn't find client {0}".format(client_id),
"status": resp.status
}]
}
raise falcon.HTTPError(resp.status, title="Client not found")
else:
resp.status = falcon.HTTP_UNAUTHORIZED
req.context["result"] = {
"errors":
[{
"id": "CLIENT_ID_NOT_FOUND",
"status": resp.status,
"type": "error",
"text": "You must pass a client id and client secret with every request"
}]
}
raise falcon.HTTPError(resp.status, title="Client info not found")
def on_get(self, req, res):
raise falcon.HTTPError(falcon.HTTP_405,
title="Client error",
description=req.method + " method not allowed.",
href=settings.__docs__)
"status": resp.status
}]
}
raise falcon.HTTPError(resp.status, "Invalid signature")
else:
resp.status = falcon.HTTP_UNAUTHORIZED
req.context["result"] = {
"errors":
[{
"type": "error",
"id": "SESSION_ID_NOT_FOUND",
"text": "This request must be authenticated with a session id",
"status": resp.status
}]
}
raise falcon.HTTPError(resp.status, "Session id not found")