A Python framework to work with micro services and AWS lambda function.
Features:
- Extendable configuration settings.
- C.O.R.S headers validation.
- HTTP Requests whitelisting.
- Request data verification. 5 Request method function routing.
- Exceptions handling.
Settings | Default |
---|---|
HTTP_METHODS | ['GET', 'POST', 'PUT', 'DELETE', 'HEAD'] |
HTTP_CONTENT_TYPE | 'application/json' |
CORS_HEADERS | ['Content-Type', 'X-Amz-Date', 'Authorization', 'X-Api-Key', 'x-requested-with'] |
CORS_ORIGINS | '*' |
CORS_X_REQUEST | '*' |
For CRUD operations define a handler function using the @route
deocorator.
The function name must include the request method as prefix ending with underscore.
from service_less import route
Codes = type('Codes', (,), {
"OK": 200
})
""" HTTP Method GET"""
@route
def get_handler() -> tuple:
return ("Hello World", Codes.OK)
""" HTTP Method POST"""
@route
def post_handler(path: str, payload: object) -> tuple:
return ({
"post_response": f"Request from '{path}' with payload '{payload}'"
}, Codes.OK)
Response type: __Tuple(JSON-serializable-object{}, int(2xx | 4xx | 5xx))
Allow the method handler function execution by adding the method in the setting list HTTP_METHODS.
# ./config.py
HTTP_METHODS=['GET', 'POST']
The request is expected to came from AWS API Gateway (RESTful API). With the @lambda_func
decorator define the main handler functionwith 2 arguments: request-event-object and method-handler-function.
from service_less import route, lambda_func
...
@lambda_func
def lambda_handler(request: dict, handler_func: callable) -> tuple:
if request.is_post():
return handler_func(request.path,
request.get_payload())
return handler_func()
Emulate a request from AWS API Gateway.
from main import lambda_handler
response = lambda_handler({
"resource": "/url/path",
"path": "/url/path",
"httpMethod": "POST",
"headers": {
"Accept": "application/json, text/javascript, */*; q=0.01",
"allow": "*",
},
"body": f"Hello World!"
}, {})
print(response)
Response:
{
"statusCode": 200,
"body": "{\"post_response\": \"Request from '/url/path' with payload 'Hello World!'\"}",
"headers":
{
"X-Requested-With": "*",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type,X-Amz-Date,Authorization,X-Api-Key,x-requested-with",
"Access-Control-Allow-Methods": "GET,POST",
"Content-Type": "application/json"
}
}