项目作者: enter-at

项目描述 :
An opinionated Python package that facilitates specifying AWS Lambda handlers including input validation, error handling and response formatting.
高级语言: Python
项目地址: git://github.com/enter-at/python-aws-lambda-handlers.git
创建时间: 2019-06-18T14:25:49Z
项目社区:https://github.com/enter-at/python-aws-lambda-handlers

开源协议:Apache License 2.0

下载


enter-at

python-aws-lambda-handlers Build Status Release Code Climate Maintainability Code Climate Test Coverage

An opinionated Python package that facilitates specifying AWS Lambda handlers including
input validation, error handling and response formatting.


It’s 100% Open Source and licensed under the APACHE2.

Quickstart

Installation

To install the latest version of lambda-handlers simply run:

  1. pip install lambda-handlers

If you are going to use validation, we have examples that work with
Marshmallow or
jsonschema.

But you can adapt a LambdaHandler to use your favourite validation module.
Please share it with us or create an issue if you need any help with that.

By default the http_handler decorator makes sure of parsing the request body
as JSON, and also formats the response as JSON with:

  1. - an adequate statusCode,
  2. - CORS headers, and
  3. - the handler return value in the body.

Basic ApiGateway Proxy Handler

  1. from lambda_handlers.handlers import http_handler
  2. @http_handler()
  3. def handler(event, context):
  4. return event['body']

Examples

HTTP handlers

Skipping the CORS headers default and configuring it.

  1. from lambda_handlers.handlers import http_handler
  2. from lambda_handlers.response import cors
  3. @http_handler(cors=cors(origin='localhost', credentials=False))
  4. def handler(event, context):
  5. return {
  6. 'message': 'Hello World!'
  7. }
  1. aws lambda invoke --function-name example response.json
  2. cat response.json
  1. {
  2. "headers":{
  3. "Access-Control-Allow-Origin": "localhost",
  4. "Content-Type": "application/json"
  5. },
  6. "statusCode": 200,
  7. "body": "{\"message\": \"Hello World!\"}"
  8. }

Validation

Using jsonschema to validate a User model as input.

  1. from typing import Any, Dict, List, Tuple, Union
  2. import jsonschema
  3. from lambda_handlers.handlers import http_handler
  4. from lambda_handlers.errors import EventValidationError
  5. class SchemaValidator:
  6. """A payload validator that uses jsonschema schemas."""
  7. @classmethod
  8. def validate(cls, instance, schema: Dict[str, Any]):
  9. """
  10. Raise EventValidationError (if any error) from validating
  11. `instance` against `schema`.
  12. """
  13. validator = jsonschema.Draft7Validator(schema)
  14. errors = list(validator.iter_errors(instance))
  15. if errors:
  16. field_errors = sorted(validator.iter_errors(instance), key=lambda error: error.path)
  17. raise EventValidationError(field_errors)
  18. @staticmethod
  19. def format_errors(errors: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
  20. """Re-format the errors from JSONSchema."""
  21. path_errors: Dict[str, List[str]] = defaultdict(list)
  22. for error in errors:
  23. path_errors[error.path.pop()].append(error.message)
  24. return [{path: messages} for path, messages in path_errors.items()]
  25. user_schema: Dict[str, Any] = {
  26. 'type': 'object',
  27. 'properties': {
  28. 'user_id': {'type': 'number'},
  29. },
  30. }
  31. @http_handler()
  32. def handler(event, context):
  33. user = event['body']
  34. SchemaValidator.validate(user, user_schema)
  35. return user
  1. aws lambda invoke --function-name example --payload '{"body": {"user_id": 42}}' response.json
  2. cat response.json
  1. {
  2. "headers":{
  3. "Access-Control-Allow-Credentials": true,
  4. "Access-Control-Allow-Origin": "*",
  5. "Content-Type": "application/json"
  6. },
  7. "statusCode": 200,
  8. "body": "{\"user_id\": 42}"
  9. }

Using Marshmallow to validate a User model as input body and response body.

  1. from typing import Any, Dict, List, Tuple, Union
  2. from marshmallow import Schema, fields, ValidationError
  3. from lambda_handlers.handlers import http_handler
  4. from lambda_handlers.errors import EventValidationError
  5. class SchemaValidator:
  6. """A data validator that uses Marshmallow schemas."""
  7. @classmethod
  8. def validate(cls, instance: Any, schema: Schema) -> Any:
  9. """Return the data or raise EventValidationError if any error from validating `instance` against `schema`."""
  10. try:
  11. return schema.load(instance)
  12. except ValidationError as error:
  13. raise EventValidationError(error.messages)
  14. class UserSchema(Schema):
  15. user_id = fields.Integer(required=True)
  16. @http_handler()
  17. def handler(event, context):
  18. user = event['body']
  19. SchemaValidator.validate(user, UserSchema())
  20. return user
  1. aws lambda invoke --function-name example --payload '{"body": {"user_id": 42}}' response.json
  2. cat response.json
  1. {
  2. "headers":{
  3. "Access-Control-Allow-Credentials": true,
  4. "Access-Control-Allow-Origin": "*",
  5. "Content-Type": "application/json"
  6. },
  7. "statusCode": 200,
  8. "body": "{\"user_id\": 42}"
  9. }
  1. aws lambda invoke --function-name example --payload '{"body": {"user_id": "peter"}}' response.json
  2. cat response.json
  1. {
  2. "headers":{
  3. "Access-Control-Allow-Credentials": true,
  4. "Access-Control-Allow-Origin": "*",
  5. "Content-Type": "application/json"
  6. },
  7. "statusCode": 400,
  8. "body": "{\"errors\": {\"user_id\": [\"Not a valid integer.\"]}"
  9. }

Headers

Cors

  1. from lambda_handlers.handlers import http_handler
  2. from lambda_handlers.response import cors
  3. @http_handler(cors=cors(origin='example.com', credentials=False))
  4. def handler(event, context):
  5. return {
  6. 'message': 'Hello World!'
  7. }
  1. aws lambda invoke --function-name example response.json
  2. cat response.json
  1. {
  2. "headers":{
  3. "Access-Control-Allow-Origin": "example.com",
  4. "Content-Type": "application/json"
  5. },
  6. "statusCode": 200,
  7. "body": "{\"message\": \"Hello World!\"}"
  8. }

Errors

  1. LambdaHandlerError
  1. BadRequestError
  1. ForbiddenError
  1. InternalServerError
  1. NotFoundError
  1. FormatError
  1. ValidationError

Share the Love

Like this project?
Please give it a ★ on our GitHub!

Check out these related projects.

  • node-aws-lambda-handlers - An opinionated Typescript package that facilitates specifying AWS Lambda handlers including
    input validation, error handling and response formatting.

Help

Got a question?

File a GitHub issue.

Contributing

Bug Reports & Feature Requests

Please use the issue tracker to report any bugs or file feature requests.

Developing

If you are interested in being a contributor and want to get involved in developing this project, we would love to hear from you!

In general, PRs are welcome. We follow the typical “fork-and-pull” Git workflow.

  1. Fork the repo on GitHub
  2. Clone the project to your own machine
  3. Commit changes to your own branch
  4. Push your work back up to your fork
  5. Submit a Pull Request so that we can review your changes

NOTE: Be sure to merge the latest changes from “upstream” before making a pull request!

License

License

See LICENSE for full details.

  1. Licensed to the Apache Software Foundation (ASF) under one
  2. or more contributor license agreements. See the NOTICE file
  3. distributed with this work for additional information
  4. regarding copyright ownership. The ASF licenses this file
  5. to you under the Apache License, Version 2.0 (the
  6. "License"); you may not use this file except in compliance
  7. with the License. You may obtain a copy of the License at
  8. https://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing,
  10. software distributed under the License is distributed on an
  11. "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  12. KIND, either express or implied. See the License for the
  13. specific language governing permissions and limitations
  14. under the License.