Python falcon.HTTPError() Examples

The following are 30 code examples of falcon.HTTPError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module falcon , or try the search function .
Example #1
Source File: errors.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def default_exception_handler(ex, req, resp, params):
    """
    Catch-all exception handler for standardized output.
    If this is a standard falcon HTTPError, rethrow it for handling
    """
    if isinstance(ex, falcon.HTTPError):
        # allow the falcon http errors to bubble up and get handled
        raise ex
    else:
        # take care of the uncaught stuff
        exc_string = traceback.format_exc()
        logging.error('Unhandled Exception being handled: \n%s', exc_string)
        format_error_resp(
            req,
            resp,
            falcon.HTTP_500,
            error_type=ex.__class__.__name__,
            message="Unhandled Exception raised: %s" % str(ex),
            retry=True
        ) 
Example #2
Source File: base_exception.py    From armada with Apache License 2.0 6 votes vote down vote up
def default_exception_handler(ex, req, resp, params):
    """
    Catch-all exception handler for standardized output.
    If this is a standard falcon HTTPError, rethrow it for handling
    """
    if isinstance(ex, falcon.HTTPError):
        # allow the falcon http errors to bubble up and get handled
        raise ex
    else:
        # take care of the uncaught stuff
        exc_string = traceback.format_exc()
        LOG.error('Unhanded Exception being handled: \n%s', exc_string)
        format_error_resp(
            req,
            resp,
            falcon.HTTP_500,
            error_type=ex.__class__.__name__,
            message="Unhandled Exception raised: %s" % str(ex),
            retry=True) 
Example #3
Source File: errors.py    From armada with Apache License 2.0 6 votes vote down vote up
def default_exception_handler(ex, req, resp, params):
    """
    Catch-all exception handler for standardized output.
    If this is a standard falcon HTTPError, rethrow it for handling
    """
    if isinstance(ex, falcon.HTTPError):
        # allow the falcon http errors to bubble up and get handled
        raise ex
    else:
        # take care of the uncaught stuff
        exc_string = traceback.format_exc()
        logging.error('Unhanded Exception being handled: \n%s', exc_string)
        format_error_resp(
            req,
            resp,
            falcon.HTTP_500,
            error_type=ex.__class__.__name__,
            message="Unhandled Exception raised: %s" % str(ex),
            retry=True
        ) 
Example #4
Source File: server.py    From og-miner with MIT License 6 votes vote down vote up
def on_post(self, request, response):
        query = dict()
        try:
            raw_json = request.stream.read()
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)
 
        try:
            data = json.loads(raw_json, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400, 'Malformed JSON')

        if "id" not in data:
            raise falcon.HTTPConflict('Task creation', "ID is not specified.")
        if "type" not in data:
            raise falcon.HTTPConflict('Task creation', "Type is not specified.")

        transaction = self.client.push_task({ "task" : "vertex", "data" : data })

        response.body = json.dumps({ "transaction" : transaction })
        response.status = falcon.HTTP_202 
Example #5
Source File: exceptions.py    From promenade with Apache License 2.0 6 votes vote down vote up
def default_exception_handler(ex, req, resp, params):
    """
    Catch-all exception handler for standardized output.
    If this is a standard falcon HTTPError, rethrow it for handling
    """
    if isinstance(ex, falcon.HTTPError):
        # allow the falcon http errors to bubble up and get handled
        raise ex
    else:
        # take care of the uncaught stuff
        exc_string = traceback.format_exc()
        LOG.error('Unhanded Exception being handled: \n%s', exc_string)
        format_error_resp(
            req,
            resp,
            falcon.HTTP_500,
            error_type=ex.__class__.__name__,
            message="Unhandled Exception raised: %s" % str(ex),
            retry=True) 
Example #6
Source File: services.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_post(req, resp):
    data = load_json_body(req)

    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute('INSERT INTO `service` (`name`) VALUES (%(name)s)', data)
        connection.commit()
    except db.IntegrityError:
        raise HTTPError('422 Unprocessable Entity',
                        'IntegrityError',
                        'service name "%(name)s" already exists' % data)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201 
Example #7
Source File: roles.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_post(req, resp):
    data = load_json_body(req)
    new_role = data['name']
    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute('INSERT INTO `role` (`name`) VALUES (%s)', new_role)
        connection.commit()
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if 'Duplicate entry' in err_msg:
            err_msg = 'role "%s" already existed' % new_role
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201 
Example #8
Source File: resources.py    From Building-Serverless-Python-Web-Services-with-Zappa with MIT License 6 votes vote down vote up
def on_get(self, req, resp):
        """Handles GET requests"""
        try:
            mobile_number = '+{}'.format(req.get_param('mobile'))
            otp = req.get_param('otp')
            otp_data = OTPModel.select().where(OTPModel.mobile_number == mobile_number, OTPModel.otp == otp, OTPModel.is_verified == False)
            if mobile_number and otp_data.exists():
                otp_data = otp_data.get()
                otp_data.is_verified = True
                otp_data.save()
                async_subscribe(mobile_number)
                resp.media = {"message": "Congratulations!!! You have successfully subscribed for daily famous quote."}
            elif mobile_number and not otp_data.exists():
                async_send_otp(mobile_number)
                resp.media = {"message": "An OTP verification has been sent on mobile {0}. To complete the subscription, Use OTP with this URL pattern https://quote-api.abdulwahid.info/subscribe?mobile={0}&otp=xxxx.".format(mobile_number)}
            else:
                raise falcon.HTTPError(falcon.HTTP_500, 'Require a valid mobile number as a query parameter. e.g https://<API_ENDPOINT>/subscribe?mobile=XXXXXXX')
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_500, str(e)) 
Example #9
Source File: users.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 
Example #10
Source File: resources.py    From Building-Serverless-Python-Web-Services-with-Zappa with MIT License 6 votes vote down vote up
def on_post(self, req, resp):
        """Handles POST requests"""
        try:
            file_object = req.get_param('file')

            # file validation
            if file_object.type != 'application/msword' or file_object.filename.split('.')[-1] != 'doc':
                raise ValueError('Please provide a valid MS Office 93 -2003 document file.')

            # calling _doc_to_text method from parser.py
            text = doc_to_text(file_object)
            quote = {
                'text': text,
                'filename': file_object.filename
            }
            resp.media = quote
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_500, str(e)) 
Example #11
Source File: manager.py    From paperboy with Apache License 2.0 5 votes vote down vote up
def handle(ex, req, resp, params):
        description = ('Sorry, couldn\'t write your thing to the '
                       'database. It worked on my box.')

        raise falcon.HTTPError(falcon.HTTP_725,
                               'Database Error',
                               description) 
Example #12
Source File: controllers.py    From python-ddd with MIT License 5 votes vote down vote up
def on_post(self, req, res):
        command = AddItemCommand({
            **req.media,
            'seller_id': req.context['user_id']
        }, strict=False)
        command_name = type(command).__name__

        if not command.is_valid():
            raise falcon.HTTPError(
                status=falcon.HTTP_400,
                title='Invalid command',
                description="{} validation failed due to {}".format(command_name, command.validation_errors())
            )

        try:
            result = self._command_bus.execute(command)
            res.status = falcon.HTTP_200
            res.body = json_response(result)
        except Exception as e:
            raise falcon.HTTPError(
                status=falcon.HTTP_400,
                title='Failed to execute {}'.format(command_name),
                description=str(e)
            )

        #     # TODO: Handle app exception
        #     pass 
Example #13
Source File: error.py    From falcon-boilerplate with MIT License 5 votes vote down vote up
def error_handler(req, resp, ex, params):
    if not isinstance(ex, falcon.HTTPError):
        logger.exception("Unhandled error while processing request: {}".format(ex))
        raise HTTPError(falcon.HTTP_INTERNAL_SERVER_ERROR, str(ex))
    else:
        raise ex 
Example #14
Source File: test_error.py    From falcon-boilerplate with MIT License 5 votes vote down vote up
def test_error_handler_raises_on_http_error():
    with pytest.raises(falcon.HTTPError) as excinfo:
        error_handler(None, None, HTTPError, None)

    assert excinfo.value.status == falcon.HTTP_INTERNAL_SERVER_ERROR 
Example #15
Source File: test_error.py    From falcon-boilerplate with MIT License 5 votes vote down vote up
def test_error_handler_raises_on_exception():
    with pytest.raises(falcon.HTTPError) as excinfo:
        error_handler(None, None, Exception, None)

    assert excinfo.value.status == falcon.HTTP_INTERNAL_SERVER_ERROR 
Example #16
Source File: test_validators.py    From falcon-boilerplate with MIT License 5 votes vote down vote up
def test_req_schema_validation_failure():
    with pytest.raises(falcon.HTTPError) as excinfo:
        Resource().request_validated(BadData(), None)

    msg = "Request data failed validation: data must contain ['message'] properties"
    assert excinfo.value.title == falcon.HTTP_BAD_REQUEST
    assert excinfo.value.description == msg 
Example #17
Source File: test_validators.py    From falcon-boilerplate with MIT License 5 votes vote down vote up
def test_resp_schema_validation_failure():
    with pytest.raises(HTTPError) as excinfo:
        Resource().response_validated(GoodData(), BadData())

    assert excinfo.value.title == falcon.HTTP_INTERNAL_SERVER_ERROR
    assert excinfo.value.description == "Response data failed validation" 
Example #18
Source File: team_subscriptions.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def on_post(req, resp, team):
    data = load_json_body(req)
    check_team_auth(team, req)
    sub_name = data.get('subscription')
    role_name = data.get('role')
    if not sub_name or not role_name:
        raise HTTPBadRequest('Invalid subscription', 'Missing subscription name or role name')
    if sub_name == team:
        raise HTTPBadRequest('Invalid subscription', 'Subscription team must be different from subscribing team')
    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute('''INSERT INTO `team_subscription` (`team_id`, `subscription_id`, `role_id`) VALUES
                          ((SELECT `id` FROM `team` WHERE `name` = %s),
                           (SELECT `id` FROM `team` WHERE `name` = %s),
                           (SELECT `id` FROM `role` WHERE `name` = %s))''',
                       (team, sub_name, role_name))
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if err_msg == 'Column \'team_id\' cannot be null':
            err_msg = 'Team "%s" not found' % team
        elif err_msg == 'Column \'role_id\' cannot be null':
            err_msg = 'Role "%s" not found' % role_name
        elif err_msg == 'Column \'subscription_id\' cannot be null':
            err_msg = 'Team "%s" not found' % sub_name
        elif err_msg.startswith('Duplicate entry'):
            err_msg = 'Subscription already exists'
        else:
            logger.exception('Unknown integrity error in team_subscriptions')
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    else:
        connection.commit()
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201 
Example #19
Source File: exceptions.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def __init__(self, message, **kwargs):
        falcon.HTTPError.__init__(self,
                                  HTTP_422,
                                  'unprocessable_entity',
                                  message,
                                  **kwargs
                                  ) 
Example #20
Source File: helpers.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def raise_not_found_exception(resource_name, resource_id, tenant_id):
    """Provides exception for not found requests (update, delete, list).

    :param resource_name: the name of the resource.
    :param resource_id: id of the resource.
    :param tenant_id: id of the tenant
    """
    msg = 'No %s method exists for tenant_id = %s id = %s' % (
        resource_name, tenant_id, resource_id)
    raise falcon.HTTPError(
        status='404 Not Found',
        title='Not Found',
        description=msg,
        code=404) 
Example #21
Source File: resource.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def resource_try_catch_block(fun):
    def try_it(*args, **kwargs):
        try:
            return fun(*args, **kwargs)

        except falcon.HTTPError:
            raise

        except exceptions.DoesNotExistException:
            raise falcon.HTTPNotFound

        except exceptions.MultipleMetricsException as ex:
            raise falcon.HTTPConflict("MultipleMetrics", str(ex))

        except exceptions.AlreadyExistsException as ex:
            raise falcon.HTTPConflict(ex.__class__.__name__, str(ex))

        except exceptions.InvalidUpdateException as ex:
            raise HTTPUnprocessableEntityError(ex.__class__.__name__, str(ex))

        except exceptions.RepositoryException as ex:
            LOG.exception(ex)
            msg = " ".join(map(str, ex.args[0].args))
            raise falcon.HTTPInternalServerError('The repository was unable '
                                                 'to process your request',
                                                 msg)

        except Exception as ex:
            LOG.exception(ex)
            raise falcon.HTTPInternalServerError('Service unavailable',
                                                 str(ex))

    return try_it 
Example #22
Source File: exceptions.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def __init__(self, message, **kwargs):
        falcon.HTTPError.__init__(self,
                                  HTTP_422,
                                  'unprocessable_entity',
                                  message,
                                  **kwargs
                                  ) 
Example #23
Source File: handlers.py    From Python-Journey-from-Novice-to-Expert with MIT License 5 votes vote down vote up
def process_request(self, req, resp):
        self.set_access_control_allow_origin(resp)

        body = req.stream.read()
        if not body:
            raise falcon.HTTPBadRequest('Empty request body',
                'A valid JSON document is required.')
        try:
            req.context['_body'] = json.loads(
                body.decode('utf-8'))
        except (ValueError, UnicodeDecodeError):
            raise falcon.HTTPError(
                falcon.HTTP_753, 'Malformed JSON',
                'JSON incorrect or not utf-8 encoded.') 
Example #24
Source File: test_exceptions.py    From freezer-api with Apache License 2.0 5 votes vote down vote up
def test_FreezerAPIException(self):
        e = exceptions.FreezerAPIException(message='testing')
        self.assertRaises(falcon.HTTPError,
                          e.handle, self.ex, self.mock_req, self.mock_req,
                          None) 
Example #25
Source File: test_exceptions.py    From freezer-api with Apache License 2.0 5 votes vote down vote up
def test_DocumentNotFound(self):
        e = exceptions.DocumentNotFound(message='testing')
        self.assertRaises(falcon.HTTPError,
                          e.handle, self.ex, self.mock_req, self.mock_req,
                          None) 
Example #26
Source File: exceptions.py    From freezer-api with Apache License 2.0 5 votes vote down vote up
def handle(ex, req, resp, params):
        raise falcon.HTTPError(_('500 unknown server error'),
                               title=_("Internal Server Error"),
                               description=FreezerAPIException.message) 
Example #27
Source File: exceptions.py    From freezer-api with Apache License 2.0 5 votes vote down vote up
def handle(ex, req, resp, params):
        raise falcon.HTTPError(
            status=falcon.status.HTTP_404,
            title=_("Not Found"),
            description=ex.message) 
Example #28
Source File: api.py    From og-miner with MIT License 5 votes vote down vote up
def on_post(self, request, response, vertex_id):
        query = dict()
        try:
            raw_json = request.stream.read()
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)
 
        try:
            data = json.loads(raw_json, encoding='utf-8')
        except ValueError:
            raise falcon.HTTPError(falcon.HTTP_400, 'Malformed JSON')
 
        data["id"] = vertex_id
        try:
            query = list(graph.query_vertices({ "id" : vertex_id }))
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)

        if len(query) > 0:
            raise falcon.HTTPConflict('Vertex Creation', "Vertex already exists.")
        
        try:
            result = graph.update_vertex(**data)
        except Exception as e:
            raise falcon.HTTPError(falcon.HTTP_400, 'Error', e.message)

        response.status = falcon.HTTP_200
        response.body = json.dumps({ "created" : result }, encoding='utf-8') 
Example #29
Source File: authentication.py    From python-ddd with MIT License 5 votes vote down vote up
def authenticate(self, req):
        if req.auth is None:
            raise falcon.HTTPError(
                status=falcon.HTTP_401,
                title='Authentication failed',
                description='Authorization header is missing'
                )

        auth_type, credentials = req.auth.split(' ')
              
        if auth_type.lower() != 'basic':
            raise falcon.HTTPError(
                status=falcon.HTTP_401,
                title='Authentication failed',
                description="Expected 'Authorization: Basic <credentials>' header"
                )

        try:
            decoded_credentials = base64.b64decode(credentials)
            login, password = decoded_credentials.decode().split(':')
        except Exception as e:
            raise falcon.HTTPError(
                status=falcon.HTTP_401,
                title='Authentication failed',
                description='Invalid credentials ({})'.format(e)
                )
        user = self._users_repository.get_user_by_login_and_password(login, password)

        if user is None:
            raise falcon.HTTPError(
                status=falcon.HTTP_401,
                title='Authentication failed',
                description='Invalid credentials'
                )
        return user 
Example #30
Source File: tenants_utils.py    From inference-model-manager with Apache License 2.0 5 votes vote down vote up
def create_tenant(parameters, id_token):
    name = parameters['name']
    cert = parameters['cert']
    scope = parameters['scope']
    quota = parameters['quota']

    logger.info('Creating new tenant: {}'
                .format(name, cert, scope, quota))

    validate_cert(cert)

    if tenant_exists(name, id_token):
        raise TenantAlreadyExistsException(name)

    try:
        create_namespace(name, quota, id_token)
        propagate_portable_secrets(target_namespace=name, id_token=id_token)
        create_bucket(name)
        create_secret(name, cert, id_token=id_token)
        create_resource_quota(name, quota, id_token=id_token)
        create_role(name, id_token=id_token)
        create_rolebinding(name, scope, id_token=id_token)
    except falcon.HTTPError:
        delete_namespace(name, id_token=id_token)
        delete_bucket(name, id_token=id_token)
        raise

    logger.info('Tenant {} created'.format(name))
    return name