Python falcon.HTTPBadRequest() Examples

The following are 30 code examples of falcon.HTTPBadRequest(). 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: common_params.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def verbosity(self, req):
        """Process the verbosity parameter

        :param req: the Falcon request object
        Valid values range from 0 (none) to 5 (maximum verbosity)
        """

        try:
            verbosity = req.get_param_as_int(
                'verbosity', required=False, min=0, max=MAX_VERBOSITY
            )
            if verbosity is not None:
                # if not set, retains the context default value.
                req.context.verbosity = verbosity
        except falcon.HTTPBadRequest as hbr:
            LOG.exception(hbr)
            raise ApiError(
                title="Invalid verbosity parameter",
                description=("If specified, verbosity parameter should be a "
                             "value from 0 to {}".format(MAX_VERBOSITY)),
                status=falcon.HTTP_400
            ) 
Example #2
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_post(self, req, resp):
        """
        Accept twilio POST that has message delivery status, and pass it
        to iris-api
        """

        try:
            re = self.iclient.post(self.endpoint, req.context['body'].decode('utf-8'), raw=True)
        except MaxRetryError:
            logger.exception('Failed posting data to iris-api')
            raise falcon.HTTPInternalServerError('Internal Server Error', 'API call failed')

        if re.status != 204:
            logger.error('Invalid response from API for delivery status update: %s', re.status)
            raise falcon.HTTPBadRequest('Likely bad params passed', 'Invalid response from API')

        resp.status = falcon.HTTP_204 
Example #3
Source File: test_falcon.py    From sentry-python with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_bad_request_not_captured(sentry_init, capture_events):
    sentry_init(integrations=[FalconIntegration()])
    events = capture_events()

    app = falcon.API()

    class Resource:
        def on_get(self, req, resp):
            raise falcon.HTTPBadRequest()

    app.add_route("/", Resource())

    client = falcon.testing.TestClient(app)

    client.simulate_get("/")

    assert not events 
Example #4
Source File: middleware.py    From falcon-multipart with MIT License 6 votes vote down vote up
def process_request(self, req, resp, **kwargs):

        if 'multipart/form-data' not in (req.content_type or ''):
            return

        # This must be done to avoid a bug in cgi.FieldStorage.
        req.env.setdefault('QUERY_STRING', '')

        # To avoid all stream consumption problem which occurs in falcon 1.0.0
        # or above.
        stream = (req.stream.stream if hasattr(req.stream, 'stream') else
                  req.stream)
        try:
            form = self.parse(stream=stream, environ=req.env)
        except ValueError as e:  # Invalid boundary?
            raise falcon.HTTPBadRequest('Error parsing file', str(e))

        for key in form:
            # TODO: put files in req.files instead when #418 get merged.
            req._params[key] = self.parse_field(form[key]) 
Example #5
Source File: token.py    From certidude with MIT License 6 votes vote down vote up
def on_put(self, req, resp):
        try:
            username, mail, created, expires, profile = self.manager.consume(req.get_param("token", required=True))
        except RelationalMixin.DoesNotExist:
            raise falcon.HTTPForbidden("Forbidden", "No such token or token expired")
        body = req.stream.read(req.content_length)
        header, _, der_bytes = pem.unarmor(body)
        csr = CertificationRequest.load(der_bytes)
        common_name = csr["certification_request_info"]["subject"].native["common_name"]
        if not common_name.startswith(username + "@"):
            raise falcon.HTTPBadRequest("Bad requst", "Invalid common name %s" % common_name)
        try:
            _, resp.body = self.authority._sign(csr, body, profile=config.PROFILES.get(profile),
                overwrite=config.TOKEN_OVERWRITE_PERMITTED)
            resp.set_header("Content-Type", "application/x-pem-file")
            logger.info("Autosigned %s as proven by token ownership", common_name)
        except FileExistsError:
            logger.info("Won't autosign duplicate %s", common_name)
            raise falcon.HTTPConflict(
                "Certificate with such common name (CN) already exists",
                "Will not overwrite existing certificate signing request, explicitly delete existing one and try again") 
Example #6
Source File: server.py    From spacy-api-docker with MIT License 6 votes vote down vote up
def on_get(self, req, resp, model_name):
        try:
            model = get_model(model_name)
            output = {
                'dep_types': get_dep_types(model),
                'ent_types': get_ent_types(model),
                'pos_types': get_pos_types(model)
            }

            resp.body = json.dumps(output, sort_keys=True, indent=2)
            resp.content_type = 'text/string'
            resp.append_header('Access-Control-Allow-Origin', "*")
            resp.status = falcon.HTTP_200
        except Exception as e:
            raise falcon.HTTPBadRequest(
                'Schema construction failed',
                '{}'.format(e)) 
Example #7
Source File: server.py    From spacy-api-docker with MIT License 6 votes vote down vote up
def on_post(self, req, resp):
        req_body = req.bounded_stream.read()
        json_data = json.loads(req_body.decode('utf8'))
        text = json_data.get('text')
        model_name = json_data.get('model', 'en')
        collapse_punctuation = json_data.get('collapse_punctuation', True)
        collapse_phrases = json_data.get('collapse_phrases', True)

        try:
            model = get_model(model_name)
            parse = Parse(model, text, collapse_punctuation, collapse_phrases)
            resp.body = json.dumps(parse.to_json(), sort_keys=True, indent=2)
            resp.content_type = 'text/string'
            resp.append_header('Access-Control-Allow-Origin', "*")
            resp.status = falcon.HTTP_200
        except Exception as e:
            raise falcon.HTTPBadRequest(
                'Dependency parsing failed',
                '{}'.format(e)) 
Example #8
Source File: server.py    From spacy-api-docker with MIT License 6 votes vote down vote up
def on_post(self, req, resp):
        req_body = req.bounded_stream.read()
        json_data = json.loads(req_body.decode('utf8'))
        text = json_data.get('text')
        model_name = json_data.get('model', 'en')
        try:
            model = get_model(model_name)
            entities = Entities(model, text)
            resp.body = json.dumps(entities.to_json(), sort_keys=True,
                                   indent=2)
            resp.content_type = 'text/string'
            resp.append_header('Access-Control-Allow-Origin', "*")
            resp.status = falcon.HTTP_200
        except Exception as e:
            raise falcon.HTTPBadRequest(
                'Text parsing failed',
                '{}'.format(e)) 
Example #9
Source File: server.py    From spacy-api-docker with MIT License 6 votes vote down vote up
def on_post(self, req, resp):
        req_body = req.bounded_stream.read()
        json_data = json.loads(req_body.decode('utf8'))
        text = json_data.get('text')
        model_name = json_data.get('model', 'en')

        try:
            model = get_model(model_name)
            sentences = Sentences(model, text)
            resp.body = json.dumps(sentences.to_json(), sort_keys=True,
                                   indent=2)
            resp.content_type = 'text/string'
            resp.append_header('Access-Control-Allow-Origin', "*")
            resp.status = falcon.HTTP_200
        except Exception as e:
            raise falcon.HTTPBadRequest(
                'Sentence tokenization failed',
                '{}'.format(e)) 
Example #10
Source File: server.py    From spacy-api-docker with MIT License 6 votes vote down vote up
def on_post(self, req, resp):
        req_body = req.bounded_stream.read()
        json_data = json.loads(req_body.decode('utf8'))
        text = json_data.get('text')
        model_name = json_data.get('model', 'en')
        collapse_punctuation = json_data.get('collapse_punctuation', False)
        collapse_phrases = json_data.get('collapse_phrases', False)

        try:
            model = get_model(model_name)
            sentences = SentencesDependencies(model,
                                              text,
                                              collapse_punctuation=collapse_punctuation,
                                              collapse_phrases=collapse_phrases)

            resp.body = json.dumps(sentences.to_json(),
                                   sort_keys=True,
                                   indent=2)
            resp.content_type = 'text/string'
            resp.append_header('Access-Control-Allow-Origin', "*")
            resp.status = falcon.HTTP_200
        except Exception as e:
            raise falcon.HTTPBadRequest(
                'Sentence tokenization and Dependency parsing failed',
                '{}'.format(e)) 
Example #11
Source File: authentication.py    From graceful with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def identify(self, req, resp, resource, uri_kwargs):
        """Identify user using Authenticate header with Token auth."""
        header = req.get_header('Authorization', False)
        auth = header.split(' ') if header else None

        if auth is None or auth[0].lower() != 'token':
            return None

        if len(auth) != 2:
            raise HTTPBadRequest(
                "Invalid Authorization header",
                "The Authorization header for Token auth should be in form:\n"
                "Authorization: Token <token_value>"
            )

        return auth[1] 
Example #12
Source File: db.py    From iris with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def guarded_session():
    '''
    Context manager that will automatically close session on exceptions
    '''
    try:
        session = Session()
        yield session
    except IrisValidationException as e:
        session.close()
        raise HTTPBadRequest('Validation error', str(e))
    except (HTTPForbidden, HTTPUnauthorized, HTTPNotFound, HTTPBadRequest):
        session.close()
        raise
    except Exception:
        session.close()
        logger.exception('SERVER ERROR')
        raise 
Example #13
Source File: test_webhook_grafana.py    From iris with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def test_parse_invalid_body():
    from iris.webhooks.grafana import grafana
    grafana_webhook = grafana()

    fake_post = {
        "evalMatches": [{
            "value": 100,
            "metric": "High value",
            "tags": "",
        }, {
            "value": 200,
            "metric": "Higher Value",
            "tags": "",
        }],
        "imageUrl": "http://grafana.org/assets/img/blog/mixed_styles.png",
        "message": "Someone is testing the alert notification within grafana.",
        "ruleId": 0,
        "ruleName": "Test notification",
        "ruleUrl": "https://grafana.org/",
        "title": "[Alerting] Test notification"
    }

    with pytest.raises(HTTPBadRequest):
        grafana_webhook.validate_post(fake_post) 
Example #14
Source File: multipart.py    From paperboy with Apache License 2.0 6 votes vote down vote up
def process_request(self, req, resp, **kwargs):

        if 'multipart/form-data' not in (req.content_type or ''):
            return

        # This must be done to avoid a bug in cgi.FieldStorage.
        req.env.setdefault('QUERY_STRING', '')

        # To avoid all stream consumption problem which occurs in falcon 1.0.0
        # or above.
        stream = (req.stream.stream if hasattr(req.stream, 'stream') else
                  req.stream)
        try:
            form = self.parse(stream=stream, environ=req.env)
        except ValueError as e:  # Invalid boundary?
            raise falcon.HTTPBadRequest('Error parsing file', str(e))

        for key in form:
            # TODO: put files in req.files instead when #418 get merged.
            req._params[key] = self.parse_field(form[key]) 
Example #15
Source File: ical_key_team.py    From oncall with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def on_post(req, resp, team):
    """Update or create the secret key that grants public access to team's
    oncall calendar for the logged-in user.

    """
    challenger = req.context['user']
    if not check_ical_team(team, challenger):
        raise HTTPBadRequest(
            'Invalid team name',
            'Team "%s" does not exist or is inactive' % team,
        )

    key = generate_ical_key()
    update_ical_key(challenger, team, 'team', key)

    resp.status = HTTP_201
    resp.body = key
    resp.set_header('Content-Type', 'text/plain') 
Example #16
Source File: helpers.py    From monasca-api with Apache License 2.0 6 votes vote down vote up
def read_json_msg_body(req):
    """Read the json_msg from the http request body and return them as JSON.

    :param req: HTTP request object.
    :return: Returns the metrics as a JSON object.
    :raises falcon.HTTPBadRequest:
    """
    try:
        msg = req.stream.read()
        json_msg = rest_utils.from_json(msg)
        return json_msg

    except rest_utils.exceptions.DataConversionException as ex:
        LOG.debug(ex)
        raise falcon.HTTPBadRequest('Bad request',
                                    'Request body is not valid JSON')
    except ValueError as ex:
        LOG.debug(ex)
        raise falcon.HTTPBadRequest('Bad request',
                                    'Request body is not valid JSON') 
Example #17
Source File: helpers.py    From monasca-api with Apache License 2.0 6 votes vote down vote up
def validate_query_dimensions(dimensions):
    """Validates the query param dimensions.

    :param dimensions: Query param dimensions.
    :raises falcon.HTTPBadRequest: If dimensions are not valid.
    """
    try:

        for key, value in dimensions.items():
            if key.startswith('_'):
                raise Exception("Dimension key {} may not start with '_'".format(key))
            metric_validation.validate_dimension_key(key)
            if value:
                if '|' in value:
                    values = value.split('|')
                    for v in values:
                        metric_validation.validate_dimension_value(key, v)
                else:
                    metric_validation.validate_dimension_value(key, value)
    except Exception as ex:
        LOG.debug(ex)
        raise HTTPUnprocessableEntityError('Unprocessable Entity', str(ex)) 
Example #18
Source File: helpers.py    From monasca-log-api with Apache License 2.0 6 votes vote down vote up
def read_json_msg_body(req):
    """Read the json_msg from the http request body and return them as JSON.

    :param req: HTTP request object.
    :return: Returns the metrics as a JSON object.
    :raises falcon.HTTPBadRequest:
    """
    try:
        body = req.media

        if body is not None:
            return body
        else:
            raise falcon.HTTPBadRequest('Bad request',
                                        'Request body is Empty')

    except rest_utils.exceptions.DataConversionException as ex:
        LOG.debug(ex)
        raise falcon.HTTPBadRequest('Bad request',
                                    'Request body is not valid JSON')
    except ValueError as ex:
        LOG.debug(ex)
        raise falcon.HTTPBadRequest('Bad request',
                                    'Request body is not valid JSON') 
Example #19
Source File: notifications.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def _parse_and_validate_notification(self, notification, require_all=False):
        """Validates the notification

        :param notification: An event object.
        :raises falcon.HTTPBadRequest
        """
        try:
            schemas_notifications.parse_and_validate(
                notification, self.valid_periods, require_all=require_all)
        except schemas_exceptions.ValidationException as ex:
            LOG.exception(ex)
            raise falcon.HTTPBadRequest('Bad Request', str(ex)) 
Example #20
Source File: test_validation.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_same_timestamps(self):
        start_time = '2015-01-01T00:00:00Z'
        end_time = start_time
        start_timestamp = helpers._convert_time_string(start_time)
        end_timestamp = helpers._convert_time_string(end_time)

        self.assertRaises(
            falcon.HTTPBadRequest,
            helpers.validate_start_end_timestamps,
            start_timestamp, end_timestamp) 
Example #21
Source File: notifications.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def _validate_notification_method_type_exist(self, nmt):
        notification_methods = self._notification_method_type_repo.list_notification_method_types()
        exists = nmt.upper() in notification_methods

        if not exists:
            LOG.warning(
                "Found no notification method type  {}."
                "Did you install/enable the plugin for that type?"
                .format(nmt))
            raise falcon.HTTPBadRequest('Bad Request', "Not a valid notification method type {} "
                                        .format(nmt)) 
Example #22
Source File: base.py    From addok with MIT License 5 votes vote down vote up
def on_get(self, req, resp, **kwargs):
        lon, lat = self.parse_lon_lat(req)
        if lon is None or lat is None:
            raise falcon.HTTPBadRequest('Invalid args', 'Invalid args')
        limit = req.get_param_as_int('limit') or 1
        filters = self.match_filters(req)
        results = reverse(lat=lat, lon=lon, limit=limit, **filters)
        self.render(req, resp, results, filters=filters, limit=limit) 
Example #23
Source File: base.py    From addok with MIT License 5 votes vote down vote up
def on_get(self, req, resp, **kwargs):
        query = req.get_param('q')
        if not query:
            raise falcon.HTTPBadRequest('Missing query', 'Missing query')
        limit = req.get_param_as_int('limit') or 5  # use config
        autocomplete = req.get_param_as_bool('autocomplete')
        if autocomplete is None:
            # Default is True.
            # https://github.com/falconry/falcon/pull/493#discussion_r44376219
            autocomplete = True
        lon, lat = self.parse_lon_lat(req)
        center = None
        if lon and lat:
            center = (lon, lat)
        filters = self.match_filters(req)
        timer = time.perf_counter()
        try:
            results = search(query, limit=limit, autocomplete=autocomplete,
                             lat=lat, lon=lon, **filters)
        except EntityTooLarge as e:
            raise falcon.HTTPRequestEntityTooLarge(str(e))
        timer = int((time.perf_counter()-timer)*1000)
        if not results:
            log_notfound(query)
        log_query(query, results)
        if config.SLOW_QUERIES and timer > config.SLOW_QUERIES:
            log_slow_query(query, results, timer)
        self.render(req, resp, results, query=query, filters=filters,
                    center=center, limit=limit) 
Example #24
Source File: login.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def on_post(req, resp):
    login_info = uri.parse_query_string(req.context['body'].decode('utf-8'))

    user = login_info.get('username')
    password = login_info.get('password')
    if user is None or password is None:
        raise HTTPBadRequest('Invalid login attempt', 'Missing user/password')

    if not auth_manager.authenticate(user, password):
        raise HTTPUnauthorized('Authentication failure', 'bad login credentials', '')

    connection = db.connect()
    cursor = connection.cursor(db.DictCursor)
    data = get_user_data(None, {'name': user}, dbinfo=(connection, cursor))
    if not data:
        cursor.close()
        connection.close()
        raise HTTPNotFound()

    session = req.env['beaker.session']
    session['user'] = user
    session.save()
    csrf_token = '%x' % SystemRandom().getrandbits(128)
    try:
        cursor.execute('INSERT INTO `session` (`id`, `csrf_token`) VALUES (%s, %s)',
                       (req.env['beaker.session']['_id'], csrf_token))
    except db.IntegrityError:
        raise HTTPBadRequest('Invalid login attempt', 'User already logged in')
    connection.commit()
    cursor.close()
    connection.close()

    # TODO: purge out of date csrf token
    data[0]['csrf_token'] = csrf_token
    resp.body = dumps(data[0]) 
Example #25
Source File: utils.py    From oncall with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def load_json_body(req):
    try:
        return json_loads(req.context['body'])
    except ValueError as e:
        raise HTTPBadRequest('invalid JSON', 'failed to decode json: %s' % str(e)) 
Example #26
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 #27
Source File: demo_server.py    From tacotron with MIT License 5 votes vote down vote up
def on_get(self, req, res):
    if not req.params.get('text'):
      raise falcon.HTTPBadRequest()
    res.data = synthesizer.synthesize(req.params.get('text'))
    res.content_type = 'audio/wav' 
Example #28
Source File: app.py    From iris-relay with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __call__(self, req, resp):
        path = self.base_url + '/v0/' + '/'.join(req.path.split('/')[4:])
        if req.query_string:
            path += '?%s' % req.query_string
        try:
            if req.method == 'POST':
                body = b''
                if req.context['body']:
                    body = req.context['body']
                result = self.iris_client.post(path, body)
            elif req.method == 'GET':
                result = self.iris_client.get(path)
            elif req.method == 'OPTIONS':
                return
            else:
                raise falcon.HTTPMethodNotAllowed(['GET', 'POST', 'PUT', 'DELETE'])
        except MaxRetryError as e:
            logger.error(e.reason)
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Max retry error, api unavailable')
        if result.status_code == 400:
            raise falcon.HTTPBadRequest('Bad Request', '')
        elif str(result.status_code)[0] != '2':
            raise falcon.HTTPInternalServerError('Internal Server Error', 'Unknown response from the api')
        else:
            resp.status = falcon.HTTP_200
            resp.content_type = result.headers['Content-Type']
            resp.body = result.content 
Example #29
Source File: attrib.py    From certidude with MIT License 5 votes vote down vote up
def on_post(self, req, resp, cn):
        namespace = ("user.%s." % self.namespace).encode("ascii")
        try:
            path, buf, cert, signed, expires = self.authority.get_signed(cn)
        except IOError:
            raise falcon.HTTPNotFound()
        else:
            for key in req.params:
                if not re.match("[a-z0-9_\.]+$", key):
                    raise falcon.HTTPBadRequest("Invalid key %s" % key)
            valid = set()
            modified = False
            for key, value in req.params.items():
                identifier = ("user.%s.%s" % (self.namespace, key)).encode("ascii")
                try:
                    if getxattr(path, identifier).decode("utf-8") != value:
                        modified = True
                except OSError: # no such attribute
                    pass
                setxattr(path, identifier, value.encode("utf-8"))
                valid.add(identifier)
            for key in listxattr(path):
                if not key.startswith(namespace):
                    continue
                if key not in valid:
                    modified = True
                    removexattr(path, key)
            if modified:
                push.publish("attribute-update", cn) 
Example #30
Source File: __init__.py    From falcon-jsonify with MIT License 5 votes vote down vote up
def bad_request(self, title, description):
        """Shortcut to respond with 400 Bad Request"""
        if self.debug:
            raise falcon.HTTPBadRequest(title, description)
        else:
            raise falcon.HTTPBadRequest()