Skip to content
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

Fix http response handling #53

Merged
merged 1 commit into from
Oct 27, 2021
Merged
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
28 changes: 21 additions & 7 deletions nitric/faas.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
ClientMessage,
TriggerRequest,
TriggerResponse,
HeaderValue,
HttpResponseContext,
TopicResponseContext,
)
Expand Down Expand Up @@ -70,12 +71,13 @@ def _grpc_response_from_ctx(ctx: TriggerContext) -> TriggerResponse:
"""
if ctx.http():
ctx = ctx.http()
headers = {k: HeaderValue(value=v) for (k, v) in ctx.res.headers.items()}
headers_old = {k: v[0] for (k, v) in ctx.res.headers.items()}
data = ctx.res.body if ctx.res.body else bytes()

return TriggerResponse(
data=ctx.res.body,
http=HttpResponseContext(
status=ctx.res.status,
headers=ctx.res.headers,
),
data=data,
http=HttpResponseContext(status=ctx.res.status, headers=headers, headers_old=headers_old),
)
elif ctx.event():
ctx = ctx.event()
Expand Down Expand Up @@ -115,7 +117,18 @@ def __init__(self, status: int = 200, headers: Record = None, body: bytes = None
"""Construct a new HttpResponse."""
self.status = status
self.headers = headers if headers else {}
self.body = body if body else bytes()
self._body = body if body else bytes()

@property
def body(self):
return self._body

@body.setter
def body(self, value: Union[str, bytes]):
if isinstance(value, str):
self._body = value.encode("utf-8")
else:
self._body = value


class HttpContext(TriggerContext):
Expand All @@ -135,7 +148,7 @@ def http(self) -> HttpContext:
def from_grpc_trigger_request(trigger_request: TriggerRequest) -> HttpContext:
"""Construct a new HttpContext from an Http trigger from the Nitric Membrane."""
if len(trigger_request.http.headers.keys()) > 0:
headers = {k: v[0].value for (k, v) in trigger_request.http.headers.items()}
headers = {k: v.value for (k, v) in trigger_request.http.headers.items()}
else:
headers = trigger_request.http.headers_old

Expand Down Expand Up @@ -334,6 +347,7 @@ async def _run(self):
else:
func = self._any_handler
response_ctx = (await func(ctx)) if asyncio.iscoroutinefunction(func) else func(ctx)

# Send function response back to server
await request_channel.send(
ClientMessage(
Expand Down