How to use lambdarest - 9 common examples

To help you get started, we’ve selected a few lambdarest 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 trustpilot / python-lambdarest / tests / test_lambdarest.py View on Github external
"cognitoAuthenticationType": None,
                    "cognitoAuthenticationProvider": None,
                    "userArn": "arn:aws:iam::123214323",
                    "userAgent": "Apache-HttpClient/4.5.x (Java/1.8.0_102)",
                    "user": "asdfsadsfads",
                },
                "resourcePath": "/test",
                "httpMethod": "POST",
                "apiId": "90o718c6bk",
            },
            "body": None,
            "isBase64Encoded": False,
        }
        self.context = {"foo": "bar"}
        self.lambda_handler = create_lambda_handler()
        self.lambda_handler_application_load_balancer = create_lambda_handler(
            application_load_balancer=True
        )
github trustpilot / python-lambdarest / tests / test_lambdarest.py View on Github external
def test_exception_in_handler_should_be_reraised(self):
        json_body = {}
        self.event["body"] = json.dumps(json_body)
        self.event["httpMethod"] = "GET"
        self.event["resource"] = "/foo/bar"

        def divide_by_zero(_):
            return 1 / 0

        self.lambda_handler = create_lambda_handler(error_handler=None)
        self.lambda_handler.handle("get", path="/foo/bar")(divide_by_zero)

        with self.assertRaises(ZeroDivisionError):
            self.lambda_handler(self.event, self.context)
github trustpilot / python-lambdarest / tests / test_lambdarest.py View on Github external
"accessKey": "asdfasdfasdfasfd",
                    "cognitoAuthenticationType": None,
                    "cognitoAuthenticationProvider": None,
                    "userArn": "arn:aws:iam::123214323",
                    "userAgent": "Apache-HttpClient/4.5.x (Java/1.8.0_102)",
                    "user": "asdfsadsfads",
                },
                "resourcePath": "/test",
                "httpMethod": "POST",
                "apiId": "90o718c6bk",
            },
            "body": None,
            "isBase64Encoded": False,
        }
        self.context = {"foo": "bar"}
        self.lambda_handler = create_lambda_handler()
        self.lambda_handler_application_load_balancer = create_lambda_handler(
            application_load_balancer=True
        )
github trustpilot / python-lambdarest / lambdarest / __init__.py View on Github external
) * (4 - response_len)

                    elif isinstance(response, dict) and all(
                        key in ["body", "statusCode", "headers", "multiValueHeaders"]
                        for key in response.keys()
                    ):
                        body = response.get("body")
                        status_code = response.get("statusCode") or status_code
                        headers = response.get("headers") or headers
                        multiValueHeaders = (
                            response.get("multiValueHeaders") or multiValueHeaders
                        )

                    else:  # if response is string, int, etc.
                        body = response
                    response = Response(body, status_code, headers, multiValueHeaders)
                return response.to_json(
                    encoder=json_encoder,
                    application_load_balancer=application_load_balancer,
                )

            except ValidationError as error:
                error_description = "Schema[{}] with value {}".format(
                    "][".join(str(error.absolute_schema_path)), error.message
                )
                logging.warning(
                    logging_message.format(status_code=400, message=error_description)
                )
                error_tuple = ("Validation Error", 400)

            except ScopeMissing as error:
                error_description = "Permission denied"
github trustpilot / python-lambdarest / lambdarest / __init__.py View on Github external
except ScopeMissing as error:
                error_description = "Permission denied"
                logging.warning(
                    logging_message.format(status_code=403, message=error_description)
                )
                error_tuple = (error_description, 403)

            except Exception as error:
                if error_handler:
                    error_handler(error, method_name)
                else:
                    raise

        body, status_code = error_tuple
        return Response(body, status_code).to_json(
            application_load_balancer=application_load_balancer
        )
github trustpilot / python-lambdarest / lambdarest / __init__.py View on Github external
# bind the mapping to an empty server name
            mapping = url_maps.bind("")
            rule, kwargs = mapping.match(path, method=method_name, return_rule=True)
            func = rule.endpoint

            # if this is a catch-all rule, don't send any kwargs
            if rule.rule == "/":
                kwargs = {}
        except NotFound as e:
            logging.warning(logging_message.format(status_code=404, message=str(e)))
            error_tuple = (str(e), 404)

        if func:
            try:
                response = func(event, **kwargs)
                if not isinstance(response, Response):
                    # Set defaults
                    status_code = headers = multiValueHeaders = None

                    if isinstance(response, tuple):
                        response_len = len(response)
                        if response_len > 3:
                            raise ValueError("Response tuple has more than 3 items")

                        # Unpack the tuple, missing items will be defaulted
                        body, status_code, headers, multiValueHeaders = response + (
                            None,
                        ) * (4 - response_len)

                    elif isinstance(response, dict) and all(
                        key in ["body", "statusCode", "headers", "multiValueHeaders"]
                        for key in response.keys()
github trustpilot / python-lambdarest / lambdarest / __init__.py View on Github external
def inner_lambda_handler(event, context=None):
        # check if running as "aws lambda proxy"
        if (
            not isinstance(event, dict)
            or not all(key in event for key in __required_keys)
            or not any(key in event for key in __either_keys)
        ):
            message = "Bad request, maybe not using Lambda Proxy?"
            logging.error(message)
            return Response(message, 500).to_json(
                application_load_balancer=application_load_balancer
            )

        # Save context within event for easy access
        event["context"] = context
        # for application load balancers, no api definition is used hence no resource is set so just use path
        if "resource" not in event:
            resource = event["path"]
        else:
            resource = event["resource"]

        # Fill placeholders in resource path
        if "pathParameters" in event:
            resource = check_update_and_fill_resource_placeholders(
                resource, event["pathParameters"]
            )
github trustpilot / python-lambdarest / lambdarest / __init__.py View on Github external
# jsonschema.validate using given schema
                        validate(json_data, schema, **__validate_kwargs)

                try:
                    provided_scopes = json.loads(
                        event["requestContext"]["authorizer"]["scopes"]
                    )
                except KeyError:
                    provided_scopes = []
                except json.decoder.JSONDecodeError:
                    # Ignore passed scopes if it isn't properly json encoded
                    provided_scopes = []

                for scope in scopes or []:
                    if scope not in provided_scopes:
                        raise ScopeMissing("Scope: '{}' is missing".format(scope))

                return func(event, *args, **kwargs)
github trustpilot / python-lambdarest / lambdarest / __init__.py View on Github external
response = Response(body, status_code, headers, multiValueHeaders)
                return response.to_json(
                    encoder=json_encoder,
                    application_load_balancer=application_load_balancer,
                )

            except ValidationError as error:
                error_description = "Schema[{}] with value {}".format(
                    "][".join(str(error.absolute_schema_path)), error.message
                )
                logging.warning(
                    logging_message.format(status_code=400, message=error_description)
                )
                error_tuple = ("Validation Error", 400)

            except ScopeMissing as error:
                error_description = "Permission denied"
                logging.warning(
                    logging_message.format(status_code=403, message=error_description)
                )
                error_tuple = (error_description, 403)

            except Exception as error:
                if error_handler:
                    error_handler(error, method_name)
                else:
                    raise

        body, status_code = error_tuple
        return Response(body, status_code).to_json(
            application_load_balancer=application_load_balancer
        )

lambdarest

flask like web framework for AWS Lambda

MIT
Latest version published 2 years ago

Package Health Score

48 / 100
Full package analysis