How to use the chalice.BadRequestError function in chalice

To help you get started, we’ve selected a few chalice 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 awslabs / aws-media-insights-engine / source / workflowapi / app.py View on Github external
200: The system configuration was set successfully successfully.
        400: Bad Request 
             - an input value is invalid
        500: Internal server error 
    """

    try:
        config = app.current_request.json_body

        logger.info(app.current_request.json_body)
        system_table = DYNAMO_RESOURCE.Table(SYSTEM_TABLE_NAME)

        # Check allowed values for known configuration parameters
        if config["Name"] == "MaxConcurrentWorkflows":
            if config["Value"] < 1:
                raise BadRequestError("MaxConcurrentWorkflows must be a value > 1")

        system_table.put_item(Item=config)
    except Exception as e:
        logger.info("Exception {}".format(e))
        raise ChaliceViewError("Exception '%s'" % e)

    return {}
github awslabs / aws-media-insights-engine / source / workflowapi / app.py View on Github external
roleArn=stageStateMachineExecutionRoleArn
        )

        stage["StateMachineArn"] = response["stateMachineArn"]

        stage["Version"] = "v0"
        stage["Id"] = str(uuid.uuid4())
        stage["Created"] = str(datetime.now().timestamp())
        stage["ResourceType"] = "STAGE"
        stage["ApiVersion"] = API_VERSION

        stage_table.put_item(Item=stage)
    
    except ValidationError as e:
        logger.error("got bad request error: {}".format(e))
        raise BadRequestError(e)
    except Exception as e:
        logger.info("Exception {}".format(e))
        stage = None
        raise ChaliceViewError("Exception '%s'" % e)

    return stage
github awslabs / aws-media-insights-engine / source / dataplaneapi / app.py View on Github external
def check_required_input(key, dict, objectname):
    if key not in dict:
        raise BadRequestError("Key '%s' is required in '%s' input" % (
            key, objectname))
github we45 / DVFaaS-Damn-Vulnerable-Functions-as-a-Service / iam_privilege_escalation / bad-dynamo-search / app.py View on Github external
try:
        jbody = app.current_request.json_body
        if isinstance(jbody, dict):
            if 'db' in jbody and 'search_term' in jbody and 'search_operator' in jbody \
                    and 'search_field' in jbody:
                db = boto3.client('dynamodb')
                response = db.scan(TableName=jbody['db'], Select='ALL_ATTRIBUTES', ScanFilter={
                    jbody['search_field']: {"AttributeValueList": [{"S": jbody['search_term']}],
                                            "ComparisonOperator": jbody['search_operator']}
                })
                if 'Items' in response:
                    return {"search_results": response['Items']}
                else:
                    return {"search_results": None}
            else:
                return BadRequestError("All parameters are required to complete the search")
        else:
            return BadRequestError("Seems to be a wrong content type")
    except Exception as e:
        return {"error": str(e)}
github awslabs / aws-media-insights-engine / source / workflowapi / app.py View on Github external
ConsistentRead=True)

        if "Item" in response:

            workflows = list_workflows_by_stage(Name)
            stage = response["Item"]

            if len(workflows) != 0 and Force == False:
                Message = """Dependent workflows were found for stage {}.
                    Either delete the dependent workflows or set the query parameter
                    force=true to delete the stage anyhow.  Undeleted dependent workflows 
                    will be kept but will contain the deleted definition of the stage.  To 
                    find the workflow that depend on a stage use the following endpoint: 
                    GET /workflow/list/stage/""".format(Name)

                raise BadRequestError(Message)

            

            # Delete the stage state machine 
            response = SFN_CLIENT.delete_state_machine(
                stateMachineArn=stage["StateMachineArn"]
            )

            response = table.delete_item(
                Key={
                    'Name': Name
                })

            flag_stage_dependent_workflows(Name)

        else:
github shaftoe / sslnotifyme / lambda / app.py View on Github external
else:
            days = 30  # set default value for days tolerance

        try:
            output = lambda_db("put_user_to_pending", user, params['domain'], days)
            if not output.get('uuid'):
                raise BadRequestError('missing expected uuid from output')
            uuid = output['uuid']
            output = lambda_mailer_blocking('send_activation_link',
                                            user, params['domain'], days, uuid)
            return process_lambda_output(output)

        except ClientError as err:
            raise BadRequestError('%s' % err)

    raise BadRequestError('must provide either domain or uuid parameter')
github sbraverman / jiralice / jiralice / chalicelib / models / schema_filter.py View on Github external
def sanitize_params(self):
        title_class = self.class_name.title().replace('/', '').replace('-', '')
        full_class = '{0}Schema'.format(title_class)
        try:
            schema_class = getattr(Schemas, full_class)()
        except Exception as e:
            raise ChaliceViewError(e)
        sanitized_params = schema_class.load(self.parameters)
        if sanitized_params.errors:
            raise BadRequestError(sanitized_params.errors)
        return sanitized_params.data
github we45 / DVFaaS-Damn-Vulnerable-Functions-as-a-Service / xxe / xxe-example / app.py View on Github external
def delete_user(email):
    try:
        hello = dict(app.current_request.headers)
        if 'authorization' in hello:
            token = hello.get('authorization')
            if token == 'admin' or token == 'staff':
                table = dynamo.Table(CV_USR_TBL)
                resp = table.delete_item(Key={
                    'email': email
                })
                if 'Error' in resp:
                    return BadRequestError("Unable to delete ")
                else:
                    return {'success': 'User with email: {} deleted'.format(email)}
            else:
                return UnauthorizedError('You are not allowed to execute this function')
        else:
            return UnauthorizedError("There's not token in your Request")
    except Exception as e:
        return BadRequestError(e)
github nedlowe / gremlin-python-example / app.py View on Github external
def setup_graph():
    try:
        graph = Graph()
        connstring = os.environ.get('GRAPH_DB')
        logging.info('Trying To Login')
        g = graph.traversal().withRemote(DriverRemoteConnection(connstring, 'g'))
        logging.info('Successfully Logged In')
    except Exception as e:  # Shouldn't really be so broad
        logging.error(e, exc_info=True)
        raise BadRequestError('Could not connect to Neptune')
    return g