How to use the falcon.HTTPError function in falcon

To help you get started, we’ve selected a few falcon examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github falconry / falcon / tests / test_middleware.py View on Github external
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
github openstack / freezer-api / tests / test_exceptions.py View on Github external
def test_DocumentNotFound(self):
        e = exceptions.DocumentNotFound(message='testing')
        self.assertRaises(falcon.HTTPError,
                          e.handle, self.ex, self.mock_req, self.mock_req, None)
github linkedin / oncall / src / oncall / api / v0 / users.py View on Github external
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
github sikrvault / sikr / sikr / resources / categories.py View on Github external
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.")
github project-lovelace / lovelace-engine / src / engine / api.py View on Github external
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
github sikrvault / sikr / sikr / resources / auth / github.py View on Github external
def on_get(self, req, res):
        raise falcon.HTTPError(falcon.HTTP_405,
                               title="Client error",
                               description=req.method + " method not allowed.",
                               href=settings.__docs__)
github sikrvault / sikr / sikr / resources / auth / facebook.py View on Github external
def on_update(self, req, res):
        raise falcon.HTTPError(falcon.HTTP_405,
                               title="Client error",
                               description=req.method + " method not allowed.",
                               href=settings.__docs__)
github ironman5366 / W.I.L.L / will / API / hooks.py View on Github external
"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")
github sikrvault / sikr / sikr / resources / auth / linkedin.py View on Github external
def on_get(self, req, res):
        raise falcon.HTTPError(falcon.HTTP_405,
                               title="Client error",
                               description=req.method + " method not allowed.",
                               href=settings.__docs__)
github ironman5366 / W.I.L.L / will / API / hooks.py View on Github external
"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")