Python falcon.HTTP_400 Examples

The following are 30 code examples of falcon.HTTP_400(). 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: configdocs_api.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def validate_content_length(self, content_length):
        """Validates that the content length header is valid

        :param content_length: the value of the content-length header.
        :returns: the validate content length value
        """
        content_length = content_length or 0
        if (content_length == 0):
            raise ApiError(
                title=('Content-Length is a required header'),
                description='Content Length is 0 or not specified',
                status=falcon.HTTP_400,
                error_list=[{
                    'message': (
                        "The Content-Length specified is 0 or not set. To "
                        "clear a collection's contents, please specify "
                        "the query parameter 'empty-collection=true'."
                        "Otherwise, a non-zero length payload and "
                        "matching Content-Length header is required to "
                        "post a collection.")
                }],
                retry=False, )
        return content_length 
Example #2
Source File: nodes.py    From drydock with Apache License 2.0 6 votes vote down vote up
def on_post(self, req, resp):
        try:
            json_data = self.req_json(req)
            node_filter = json_data.get('node_filter', None)
            design_ref = json_data.get('design_ref', None)
            if design_ref is None:
                self.info(req.context, 'Missing required input value: design_ref')
                self.return_error(
                    resp,
                    falcon.HTTP_400,
                    message='Missing input required value: design_ref',
                    retry=False)
                return
            _, site_design = self.orchestrator.get_effective_site(design_ref)
            nodes = self.orchestrator.process_node_filter(node_filter=node_filter,
                                                          site_design=site_design)
            resp_list = [n.name for n in nodes if nodes]

            resp.body = json.dumps(resp_list)
            resp.status = falcon.HTTP_200
        except Exception as ex:
            self.error(req.context, "Unknown error: %s" % str(ex), exc_info=ex)
            self.return_error(
                resp, falcon.HTTP_500, message="Unknown error", retry=False) 
Example #3
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_validate_design(self, req, resp, json_data):
        """Create async task for validate design."""
        action = json_data.get('action', None)

        if action != 'validate_design':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_validate_design"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #4
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_prepare_site(self, req, resp, json_data):
        """Create async task for prepare site."""
        action = json_data.get('action', None)

        if action != 'prepare_site':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_prepare_site"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #5
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_verify_nodes(self, req, resp, json_data):
        """Create async task for verify node."""
        action = json_data.get('action', None)

        if action != 'verify_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_verify_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #6
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_prepare_nodes(self, req, resp, json_data):
        """Create async task for prepare node."""
        action = json_data.get('action', None)

        if action != 'prepare_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_prepare_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #7
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_deploy_nodes(self, req, resp, json_data):
        """Create async task for deploy node."""
        action = json_data.get('action', None)

        if action != 'deploy_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_deploy_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #8
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_destroy_nodes(self, req, resp, json_data):
        """Create async task for destroy node."""
        action = json_data.get('action', None)

        if action != 'destroy_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_destroy_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #9
Source File: insert.py    From LicenseServer with MIT License 6 votes vote down vote up
def recordUser(session, valueDict):
        userRow = None
        requiredValues = ["Signature", "Name", "Email", "UserID"]

        for value in requiredValues:
            if value not in valueDict.keys():
                return None
                #resp.body = "Error, missing key {}".format(value)
                #resp.status = falcon.HTTP_400

        # User table values
        signature = valueDict.get("Signature")
        name = valueDict.get("Name")
        email = valueDict.get("Email")
        company = valueDict.get("Company")
        userID = valueDict.get("UserID")

        userExists = True
        userRow = session.query(UsersTable).get((signature, userID))    

        if userRow is None:
            userExists = False
            userRow = UsersTable(Signature=signature, Name=name, Email=email, Company=company, UserID=userID, InstallDateTime=ctime())

        return userRow, userExists 
Example #10
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 #11
Source File: configdocs_helper.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def add_messages_to_validation_status(status, msgs, level):
    """Given a status retrieved from _format_validations_to_status and a list
    of messages at a given level (Error, Warning, Info), add messages to the
    status
    """
    code = falcon.HTTP_200
    if str(level).lower() == 'error':
        code = falcon.HTTP_400
        status['status'] = 'Failure'
        status['message'] = 'Validations failed'
        status['code'] = code
        status['details']['errorCount'] += len(msgs)

    formatted_messages = []
    for msg in msgs:
        formatted_messages.append({'code': code,
                                   'message': msg,
                                   'status': str(level).capitalize(),
                                   'level': str(level).lower()})
    status['details']['messageList'] += formatted_messages 
Example #12
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_destroy_nodes(self, req, resp, json_data):
        """Create async task for destroy node."""
        action = json_data.get('action', None)

        if action != 'destroy_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_destroy_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #13
Source File: configdocs_helper.py    From shipyard with Apache License 2.0 6 votes vote down vote up
def _format_validations_to_status(val_msgs, error_count):
    """Using a list of validation messages and an error count,
    formulates and returns a status response dict
    """
    status = 'Success'
    message = 'Validations succeeded'
    code = falcon.HTTP_200
    if error_count > 0:
        status = 'Failure'
        message = 'Validations failed'
        code = falcon.HTTP_400

    return {
        "kind": "Status",
        "apiVersion": "v1.0",
        "metadata": {},
        "status": status,
        "message": message,
        "reason": "Validation",
        "details": {
            "errorCount": error_count,
            "messageList": val_msgs,
        },
        "code": code
    } 
Example #14
Source File: nodes.py    From drydock with Apache License 2.0 6 votes vote down vote up
def on_post(self, req, resp):
        try:
            json_data = self.req_json(req)
            node_filter = json_data.get('node_filter', None)
            design_ref = json_data.get('design_ref', None)
            if design_ref is None:
                self.info(req.context,
                          'Missing required input value: design_ref')
                self.return_error(
                    resp,
                    falcon.HTTP_400,
                    message='Missing input required value: design_ref',
                    retry=False)
                return
            _, site_design = self.orchestrator.get_effective_site(design_ref)
            nodes = self.orchestrator.process_node_filter(
                node_filter=node_filter, site_design=site_design)
            resp_list = [n.name for n in nodes if nodes]

            resp.body = json.dumps(resp_list)
            resp.status = falcon.HTTP_200
        except Exception as ex:
            self.error(req.context, "Unknown error: %s" % str(ex), exc_info=ex)
            self.return_error(
                resp, falcon.HTTP_500, message="Unknown error", retry=False) 
Example #15
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_validate_design(self, req, resp, json_data):
        """Create async task for validate design."""
        action = json_data.get('action', None)

        if action != 'validate_design':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_validate_design"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #16
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_prepare_site(self, req, resp, json_data):
        """Create async task for prepare site."""
        action = json_data.get('action', None)

        if action != 'prepare_site':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_prepare_site"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #17
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_deploy_nodes(self, req, resp, json_data):
        """Create async task for deploy node."""
        action = json_data.get('action', None)

        if action != 'deploy_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_deploy_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #18
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_verify_nodes(self, req, resp, json_data):
        """Create async task for verify node."""
        action = json_data.get('action', None)

        if action != 'verify_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_verify_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #19
Source File: tasks.py    From drydock with Apache License 2.0 6 votes vote down vote up
def task_prepare_nodes(self, req, resp, json_data):
        """Create async task for prepare node."""
        action = json_data.get('action', None)

        if action != 'prepare_nodes':
            self.error(
                req.context,
                "Task body ended up in wrong handler: action %s in task_prepare_nodes"
                % action)
            self.return_error(
                resp, falcon.HTTP_500, message="Error", retry=False)

        try:
            task = self.create_task(json_data, req.context)
            resp.body = json.dumps(task.to_dict())
            resp.append_header('Location',
                               "/api/v1.0/tasks/%s" % str(task.task_id))
            resp.status = falcon.HTTP_201
        except errors.InvalidFormat as ex:
            self.error(req.context, ex.msg)
            self.return_error(
                resp, falcon.HTTP_400, message=ex.msg, retry=False) 
Example #20
Source File: action_helper.py    From shipyard with Apache License 2.0 5 votes vote down vote up
def parse_step_id(**kwargs):
        """
        Retreive step_id from the input parameters
        """
        step_id = kwargs.get('step_id')
        if step_id is None:
            raise ApiError(
                title='Missing Step ID!',
                description='Missing Step ID',
                status=falcon.HTTP_400)

        LOG.debug("Step ID parsed: %s", step_id)

        return step_id 
Example #21
Source File: action_helper.py    From shipyard with Apache License 2.0 5 votes vote down vote up
def parse_action_id(**kwargs):
        """
        Retreive action_id from the input parameters
        Action_id must be a 26 character ulid.
        """
        action_id = kwargs.get('action_id')
        if action_id is None or not len(action_id) == 26:
            raise ApiError(
                title='Invalid Action ID!',
                description='An invalid action ID was specified',
                status=falcon.HTTP_400)

        LOG.debug("Action ID parsed: %s", action_id)

        return action_id 
Example #22
Source File: validate_deployment_action.py    From shipyard with Apache License 2.0 5 votes vote down vote up
def validate(self):
        results = self.doc_val_mgr.validate()
        if self.doc_val_mgr.errored:
            if self.cont_on_fail:
                LOG.warn("Validation failures occured, but 'continue-on-fail' "
                         "is set to true. Processing continues")
            else:
                raise ApiError(
                    title='Document validation failed',
                    description='InvalidConfigurationDocuments',
                    status=falcon.HTTP_400,
                    error_list=results,
                    retry=False,
                ) 
Example #23
Source File: test_logs.py    From monasca-api with Apache License 2.0 5 votes vote down vote up
def test_should_fail_not_delegate_ok_cross_tenant_id(self, _):
        _init_resource(self)
        response = self.simulate_request(
            path='/logs',
            method='POST',
            query_string='tenant_id=1',
            headers={
                'X-Roles': ROLES,
                'Content-Type': 'application/json',
                'Content-Length': '0'
            }
        )
        self.assertEqual(falcon.HTTP_400, response.status) 
Example #24
Source File: test_versions.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def test_should_fail_for_unsupported_version(self):
        unsupported_version = 'v5.0'
        uri = _get_versioned_url(unsupported_version)

        res = self.simulate_request(
            path=uri,
            method='GET',
            headers={
                'Content-Type': 'application/json'
            }
        )

        self.assertEqual(falcon.HTTP_400, res.status) 
Example #25
Source File: test_logs_v3.py    From monasca-log-api with Apache License 2.0 5 votes vote down vote up
def test_should_fail_not_delegate_ok_cross_tenant_id(self, _):
        _init_resource(self)
        res = self.simulate_request(
            path='/logs',
            method='POST',
            query_string='tenant_id=1',
            headers={
                headers.X_ROLES.name: ROLES,
                'Content-Type': 'application/json',
                'Content-Length': '0'
            }
        )
        self.assertEqual(falcon.HTTP_400, res.status) 
Example #26
Source File: workflows_api.py    From shipyard with Apache License 2.0 5 votes vote down vote up
def get_workflow_detail(self, helper, workflow_id):
        """
        Retrieve a workflow by id,
        :param helper: The WorkflowHelper constructed for this invocation
        :param workflow_id: a string in {dag_id}__{execution_date} format
                            identifying a workflow
        :returns: a workflow detail dictionary including steps
        """
        if not WorkflowHelper.validate_workflow_id(workflow_id):
            raise ApiError(
                title='Invalid Workflow ID specified',
                description=(
                    'Workflow id must use {dag id}__{execution date} format',
                ),
                status=falcon.HTTP_400,
                retry=False,
            )
        workflow = helper.get_workflow(workflow_id=workflow_id)
        if workflow is None:
            raise ApiError(
                title='Workflow not found',
                description=(
                    'A Workflow with id {} was not found'.format(workflow_id),
                ),
                status=falcon.HTTP_404,
                retry=False,
            )
        return workflow 
Example #27
Source File: controllers.py    From python-ddd with MIT License 5 votes vote down vote up
def on_get(self, req, res):
        query = GetItemsQuery()
        if not query.is_valid():
            res.status = falcon.HTTP_400
            # TODO: Add error details
            return

        result = self._query_bus.execute(query)
        res.body = json_response(result)
        res.status = falcon.HTTP_200 
Example #28
Source File: configdocs_helper.py    From shipyard with Apache License 2.0 5 votes vote down vote up
def get_rendered_configdocs(self, version=BUFFER, cleartext_secrets=False):
        """Returns the rendered configuration documents for the specified
        revision (by name BUFFER, COMMITTED, LAST_SITE_ACTION,
        SUCCESSFUL_SITE_ACTION)
        """
        revision_dict = self._get_revision_dict()

        # Raise Exceptions if we received unexpected version
        if version not in [BUFFER, COMMITTED, LAST_SITE_ACTION,
                           SUCCESSFUL_SITE_ACTION]:
            raise ApiError(
                title='Invalid version',
                description='{} is not a valid version'.format(version),
                status=falcon.HTTP_400,
                retry=False)

        if revision_dict.get(version):
            revision_id = revision_dict.get(version).get('id')

            try:
                return self.deckhand.get_rendered_docs_from_revision(
                    cleartext_secrets=cleartext_secrets,
                    revision_id=revision_id)
            except DeckhandError as de:
                raise ApiError(
                    title='Deckhand indicated an error while rendering',
                    description=de.response_message,
                    status=falcon.HTTP_500,
                    retry=False)

        else:
            raise ApiError(
                title='This revision does not exist',
                description='{} version does not exist'.format(version),
                status=falcon.HTTP_404,
                retry=False) 
Example #29
Source File: validate_target_nodes.py    From shipyard with Apache License 2.0 5 votes vote down vote up
def validate(self):
        parameters = self.action.get('parameters')
        valid = parameters is not None
        if valid:
            # target_nodes parameter should exist
            nodes = parameters.get('target_nodes')
            valid = nodes is not None
        if valid:
            # should be able to listify the nodes
            try:
                node_list = list(nodes)
                valid = len(node_list) > 0
            except TypeError:
                valid = False
        if valid:
            # each entry should be a string
            for s in node_list:
                if not isinstance(s, str):
                    valid = False
                    break
        if valid:
            # all valid
            return

        # something was invalid
        raise ApiError(
            title='Invalid target_nodes parameter',
            description=(
                'The target_nodes parameter for this action '
                'should be a list with one or more string values '
                'representing node names'
            ),
            status=falcon.HTTP_400,
            retry=False
        ) 
Example #30
Source File: designs.py    From drydock with Apache License 2.0 5 votes vote down vote up
def on_post(self, req, resp):
        """Method handler for POST requests.

        :param req: Falcon request object
        :param resp: Falcon response object
        """
        try:
            json_data = self.req_json(req)
            design = None
            if json_data is not None:
                base_design = json_data.get('base_design_id', None)

                if base_design is not None:
                    base_design = uuid.UUID(base_design)
                    design = hd_objects.SiteDesign(base_design_id=base_design)
            else:
                design = hd_objects.SiteDesign()
            design.assign_id()
            design.create(req.context, self.state_manager)

            resp.body = json.dumps(design.obj_to_simple())
            resp.status = falcon.HTTP_201
        except errors.StateError:
            self.error(req.context, "Error updating persistence")
            self.return_error(
                resp,
                falcon.HTTP_500,
                message="Error updating persistence",
                retry=True)
        except errors.InvalidFormat as fex:
            self.error(req.context, str(fex))
            self.return_error(
                resp, falcon.HTTP_400, message=str(fex), retry=False)