Skip to content

WIP - Version 6 #52

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
111 changes: 60 additions & 51 deletions example/handler.py
Original file line number Diff line number Diff line change
@@ -1,83 +1,92 @@
"""app: handle requests."""

from typing import Dict, Tuple
import typing.io

import json
from typing import Dict

from lambda_proxy.proxy import API
from lambda_proxy.responses import PlainTextResponse, Response

app = API(name="app", debug=True)


@app.get("/", cors=True)
def main() -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", "Yo")


@app.get("/<regex([0-9]{2}-[a-zA-Z]{5}):regex1>", cors=True)
def _re_one(regex1: str) -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", regex1)

app = API(name="app")

@app.get("/<regex([0-9]{1}-[a-zA-Z]{5}):regex2>", cors=True)
def _re_two(regex2: str) -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", regex2)

@app.get("/", cors=True, response_class=PlainTextResponse)
def main():
"""Return String."""
return "Yo"

@app.post("/people", cors=True)
def people_post(body) -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", body)

@app.post("/people", cors=True, response_class=PlainTextResponse)
def people_post(body):
"""Return String."""
return body

@app.get("/people", cors=True)
def people_get() -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", "Nope")


@app.get("/<string:user>", cors=True)
@app.get("/<string:user>/<int:num>", cors=True)
def double(user: str, num: int = 0) -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", f"{user}-{num}")
@app.get("/people", cors=True, response_class=PlainTextResponse)
def people_get():
"""Return String."""
return "Nope"


@app.get("/kw/<string:user>", cors=True)
def kw_method(user: str, **kwargs: Dict) -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", f"{user}")
@app.get("/kw/<string:user>", cors=True, response_class=PlainTextResponse)
def kw_method(user: str, **kwargs: Dict):
"""Return String."""
return f"{user}"


@app.get("/ctx/<string:user>", cors=True)
@app.get("/ctx/<string:user>", cors=True, response_class=PlainTextResponse)
@app.pass_context
@app.pass_event
def ctx_method(evt: Dict, ctx: Dict, user: str, num: int = 0) -> Tuple[str, str, str]:
"""Return JSON Object."""
return ("OK", "text/plain", f"{user}-{num}")
def ctx_method(evt: Dict, ctx: Dict, user: str, num: int = 0):
"""Return String."""
return f"{user}-{num}"


@app.get("/json", cors=True)
def json_handler() -> Tuple[str, str, str]:
@app.get("/json/itworks", cors=True)
def json_handler():
"""Return JSON Object."""
return ("OK", "application/json", json.dumps({"app": "it works"}))
return {"app": "it works"}


@app.get("/binary", cors=True, payload_compression_method="gzip")
def bin() -> Tuple[str, str, typing.io.BinaryIO]:
def bin():
"""Return image."""
with open("./rpix.png", "rb") as f:
return ("OK", "image/png", f.read())
return Response(f.read(), media_type="image/png")


@app.get(
"/b64binary", cors=True, payload_compression_method="gzip", binary_b64encode=True,
)
def b64bin() -> Tuple[str, str, typing.io.BinaryIO]:
def b64bin():
"""Return base64 encoded image."""
with open("./rpix.png", "rb") as f:
return ("OK", "image/png", f.read())
return Response(f.read(), media_type="image/png")


@app.get("/header/json", cors=True)
def addHeader_handler(resp: Response):
"""Return JSON Object."""
resp.headers["Cache-Control"] = "max-age=3600"
return {"app": "it works"}


@app.get("/<string:user>", cors=True, response_class=PlainTextResponse)
@app.get("/<string:user>/<int:num>", cors=True, response_class=PlainTextResponse)
def double(user: str, num: int = 0):
"""Return String."""
return f"{user}-{num}"


@app.get(
"/<regex([0-9]{2}-[a-zA-Z]{5}):regex1>", cors=True, response_class=PlainTextResponse
)
def _re_one(regex1: str):
"""Return String."""
return regex1


@app.get(
"/<regex([0-9]{1}-[a-zA-Z]{5}):regex2>", cors=True, response_class=PlainTextResponse
)
def _re_two(regex2: str):
"""Return String."""
return regex2
29 changes: 29 additions & 0 deletions lambda_proxy/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""
lambda-proxy Errors.

Original code from
- https://github.com/encode/starlette/blob/master/starlette/exceptions.py
- https://github.com/tiangolo/fastapi/blob/master/fastapi/exceptions.py
"""

import http


class HTTPException(Exception):
"""Base HTTP Execption for lambda-proxy."""

def __init__(
self, status_code: int, detail: str = None, headers: dict = None
) -> None:
"""Set Exception."""
if detail is None:
detail = http.HTTPStatus(status_code).phrase

self.status_code = status_code
self.detail = detail
self.headers = headers

def __repr__(self) -> str:
"""Exception repr."""
class_name = self.__class__.__name__
return f"{class_name}(status_code={self.status_code!r}, detail={self.detail!r})"
Loading