Skip to content

add options to routes #47

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGES.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
Changes
=======
5.3.0 (TBD)
- forward `body` on PUT and PATCH method (#46, author kelsta)
- add 'OPTIONS' to routes.

5.2.0 (2020-04-09)
- change `api.routes` to list to allow path per methods
(e.g you can now add route with the same path but with different methods).
Expand Down
86 changes: 86 additions & 0 deletions lambda_proxy/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,7 @@ def __init__(
configure_logs: bool = True,
debug: bool = False,
https: bool = True,
automatic_options: bool = True,
) -> None:
"""Initialize API object."""
self.name: str = name
Expand All @@ -198,6 +199,7 @@ def __init__(
self.request_path: ApigwPath
self.debug: bool = debug
self.https: bool = https
self.automatic_options: bool = automatic_options
self.log = logging.getLogger(self.name)
if configure_logs:
self._configure_logging()
Expand Down Expand Up @@ -393,6 +395,9 @@ def _add_route(self, path: str, endpoint: Callable, **kwargs) -> None:
"URL paths must be unique.".format(path)
)

if "OPTIONS" not in methods and self.automatic_options:
methods.append("OPTIONS")

route = RouteEntry(
endpoint,
path,
Expand Down Expand Up @@ -477,6 +482,46 @@ def _register_view(endpoint):

return _register_view

def put(self, path: str, **kwargs) -> Callable:
"""Register PUT route."""
kwargs.update(dict(methods=["PUT"]))

def _register_view(endpoint):
self._add_route(path, endpoint, **kwargs)
return endpoint

return _register_view

def patch(self, path: str, **kwargs) -> Callable:
"""Register PATCH route."""
kwargs.update(dict(methods=["PATCH"]))

def _register_view(endpoint):
self._add_route(path, endpoint, **kwargs)
return endpoint

return _register_view

def options(self, path: str, **kwargs) -> Callable:
"""Register OPTIONS route."""
raise NotImplementedError("OPTIONS is not implemented")

def head(self, path: str, **kwargs) -> Callable:
"""Register HEAD route."""
raise NotImplementedError("HEAD is not implemented")

def delete(self, path: str, **kwargs) -> Callable:
"""Register DELETE route."""
raise NotImplementedError("DELETE is not implemented")

def connect(self, path: str, **kwargs) -> Callable:
"""Register CONNECT route."""
raise NotImplementedError("CONNECT is not implemented")

def trace(self, path: str, **kwargs) -> Callable:
"""Register TRACE route."""
raise NotImplementedError("TRACE is not implemented")

def pass_context(self, f: Callable) -> Callable:
"""Decorator: pass the API Gateway context to the function."""

Expand Down Expand Up @@ -537,6 +582,36 @@ def _redoc_ui_html() -> Tuple[str, str, str]:

self._add_route("/redoc", _redoc_ui_html, cors=True, tag=["documentation"])

def preflight_response(
self,
accepted_methods: Sequence = [],
allow_origins: Sequence = (),
allow_credentials: bool = True,
cache_control: Optional[str] = None,
):
"""Create preflight response."""
messageData: Dict[str, Any] = {
"statusCode": 200,
"headers": {"Content-Type": "text/plain"},
}

# https://github.com/encode/starlette/blob/master/starlette/middleware/cors.py#L41-L51
if "*" in allow_origins:
messageData["headers"]["Access-Control-Allow-Origin"] = "*"
else:
messageData["headers"]["Vary"] = "Origin"

if allow_credentials:
messageData["headers"]["Access-Control-Allow-Credentials"] = "true"

messageData["headers"]["Access-Control-Allow-Methods"] = ",".join(
accepted_methods
)
if cache_control:
messageData["headers"]["Cache-Control"] = cache_control

return messageData

def response(
self,
status: Union[int, str],
Expand Down Expand Up @@ -677,6 +752,17 @@ def __call__(self, event, context):
),
)

if http_method == "OPTIONS":
params = {}
if route_entry.cors:
params["allow_origins"] = "*"
params["allow_credentials"] = True
return self.preflight_response(
accepted_methods=route_entry.methods,
cache_control=route_entry.cache_control,
**params,
)

request_params = event.get("queryStringParameters", {}) or {}
if route_entry.token:
if not self._validate_token(request_params.get("access_token")):
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

setup(
name="lambda-proxy",
version="5.2.0",
version="5.3.0",
description=u"Simple AWS Lambda proxy to handle API Gateway request",
long_description=readme,
long_description_content_type="text/markdown",
Expand Down
Loading