How to use the falcon.HTTP_400 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 airshipit / promenade / tests / unit / api / test_validatedesign.py View on Github external
def test_post_validatedesign_empty_docs(client, std_body, std_headers):
    with mock.patch('promenade.design_ref.get_documents') as gd:
        gd.return_value = ([], False)
        response = client.simulate_post(
            '/api/v1.0/validatedesign', headers=std_headers, body=std_body)
    assert response.status == falcon.HTTP_400
    assert response.json['details']['errorCount'] == 5
github mislavcimpersak / xkcd-excuse-generator / tests / test_function.py View on Github external
def test_excuse__why_too_long():
    ERROR_CODE = 1021
    response = hug.test.get(app, '/v1/excuse/', {'who': '0', 'why': 'my code is compiling my code is compiling ', 'what': '0'})

    assert response.status == HTTP_400
    assert response.data['errors'][0]['code'] == ERROR_CODE
github sgaynetdinov / instasave_bot / tests / falcon / tests_middleware_secret_key.py View on Github external
def test_invalid_secret(self):
        got = self.simulate_post('/', body=b'{"secret": "INVALID_SECRET", "type": "message_new"}')

        self.assertEqual(got.json['title'], 'Invalid SECRET_KEY')
        self.assertEqual(got.status, falcon.HTTP_400)
github openstack / zaqar / tests / unit / queues / transport / wsgi / test_queue_lifecycle.py View on Github external
def test_empty_project_id(self):
        path = '/v1/queues/gumshoe'

        self.simulate_get(path, '')
        self.assertEqual(self.srmock.status, falcon.HTTP_400)

        self.simulate_put(path, '')
        self.assertEqual(self.srmock.status, falcon.HTTP_400)

        self.simulate_head(path, '')
        self.assertEqual(self.srmock.status, falcon.HTTP_400)

        self.simulate_delete(path, '')
        self.assertEqual(self.srmock.status, falcon.HTTP_400)
github att-comdev / shipyard / shipyard_airflow / control / airflow_dag_state.py View on Github external
def on_get(self, req, resp, dag_id, execution_date):
        # Retrieve URL
        web_server_url = self.retrieve_config('base', 'web_server')

        if 'Error' in web_server_url:
            resp.status = falcon.HTTP_500
            raise falcon.HTTPInternalServerError("Internal Server Error",
                                                 "Missing Configuration File")
        else:
            req_url = ('{}/admin/rest_api/api?api=dag_state&dag_id={}'
                       '&execution_date={}'.format(web_server_url, dag_id,
                                                   execution_date))
            response = requests.get(req_url).json()

            if response["output"]["stderr"]:
                resp.status = falcon.HTTP_400
                resp.body = response["output"]["stderr"]
                return
            else:
                resp.status = falcon.HTTP_200
                resp.body = response["output"]["stdout"]
github uyamazak / oceanus / oceanus / www / pirate.py View on Github external
{'type': 'string',
                     'empty': True,
                     'nullable': True,
                     'regex': '^[0-9a-zA-Z\-(\)_\s]*$',
                     'maxlength': 16}
                   )
        }
        user_data = self.adjust_user_data({k: v[0]
                                           for k, v in item_dict.items()})
        v = Validator({k: v[1] for k, v in item_dict.items()})
        validate_result = v.validate(user_data)

        if validate_result:
            resp.status = falcon.HTTP_200
        else:
            resp.status = falcon.HTTP_400
            return

        user_data['jsn'] = self.clean_json(user_data['jsn'])
        redis_data = json.dumps(user_data)
        redis_result = self.write_to_redis(site_name, redis_data)
        if not redis_result:
            self.logger.error("writing Redis failed.\n"
                              "{}\n"
                              "{}".format(redis_result, redis_data))
            resp.status = falcon.HTTP_500

        if req.get_param('debug', required=False):
            resp.body = "oceanus pirate debug" \
                        + "\n\n site_name:" + site_name \
                        + "\n\n user_data:\n" + pformat(user_data) \
                        + '\n\n validate: ' + pformat(validate_result) \
github openstack / barbican / barbican / api / resources.py View on Github external
def _secret_not_in_order(req, resp):
    """Throw exception that secret info is not available in the order."""
    api.abort(falcon.HTTP_400,
              u._("Secret metadata expected but not received."), req, resp)
github att-comdev / shipyard / shipyard_airflow / control / airflow_trigger_dag.py View on Github external
if 'Error' in web_server_url:
            resp.status = falcon.HTTP_500
            raise falcon.HTTPInternalServerError("Internal Server Error",
                                                 "Missing Configuration File")
        else:
            # "conf" - JSON string that gets pickled into the DagRun's
            # conf attribute
            req_url = ('{}/admin/rest_api/api?api=trigger_dag&dag_id={}'
                       '&conf={}'.format(web_server_url, dag_id, conf))

            response = requests.get(req_url).json()

            # Returns error response if API call returns
            # response code other than 200
            if response["http_response_code"] != 200:
                resp.status = falcon.HTTP_400
                resp.body = response["output"]
                return
            else:
                # Returns 201 if action is created successfully
                resp.status = falcon.HTTP_201

                # Return time of execution so that we can use
                # it to query dag/task status
                dt = parse(response["response_time"])
                resp.body = dt.strftime('%Y-%m-%dT%H:%M:%S')
github Ermlab / python-ddd / infrastructure / framework / falcon / controllers.py View on Github external
def on_post(self, req, res):
        command = AddItemCommand(req.media, strict=False)
        if not command.is_valid():
            res.status = falcon.HTTP_400
            # TODO: Add error details
            return
        # try:
        result = self._command_bus.execute(command)
        res.body = json_response(result)
        res.status = falcon.HTTP_200
        # TODO: change to ActionResult (metadata - status, data, etc.)
github wellcometrust / reach / web / web / views / opt_search.py View on Github external
def on_get(self, req, resp):
        """Returns the result of a search on the elasticsearch cluster.

        Args:
            req: The request passed to this controller
            resp: The reponse object to be returned
        """

        if req.params:
            if not req.params.get('terms'):
                resp.body = json.dumps({
                    'status': 'error',
                    'message': "The request doesn't contain anything to search"
                })
                resp.status = falcon.HTTP_400

            status, response, count = _search_db(self.db, req.params, self.source)


            if status:
                if 'citations' in self.source:
                    # Clean dataset a bit before using in JS
                    # response = format_citation(response)
                    pass
                resp.body = json.dumps({'status': 'success', 'data': response, 'hits': count})
            else:
                resp.body = json.dumps({
                    'status': 'error',
                    'message': response
                })
        else: