Skip to content

Commit

Permalink
[New] http,server: onClose response support
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastien committed Oct 2, 2024
1 parent 54c3a10 commit 2afd3c1
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
7 changes: 6 additions & 1 deletion src/py/extra/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
from .http.model import HTTPRequest, HTTPResponse, HTTPRequestError # NOQA: F401
from .http.model import (
HTTPRequest,
HTTPResponse,
HTTPResponseLine,
HTTPRequestError,
) # NOQA: F401
from .decorators import on, expose, pre, post # NOQA: F401
from .server import run # NOQA: F401
from .model import Service # NOQA: F401
Expand Down
9 changes: 8 additions & 1 deletion src/py/extra/http/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -551,7 +551,7 @@ def Create(
protocol=protocol,
)

__slots__ = ["protocol", "status", "message", "headers", "body"]
__slots__ = ["protocol", "status", "message", "headers", "body", "_onClose"]

def __init__(
self,
Expand All @@ -569,6 +569,7 @@ def __init__(
# don't support that.
self.headers: HTTPHeaders = headers
self.body: THTTPBody | None = body
self._onClose: Callable[[HTTPResponse], None] | None = None

# TODO: Deprecate
def getHeader(self, name: str) -> str | None:
Expand Down Expand Up @@ -600,6 +601,12 @@ def head(self) -> bytes:
# TODO: UTF8 maybe? Why ASCII?
return "\r\n".join(lines).encode("ascii")

def onClose(
self, callback: Callable[["HTTPResponse"], None] | None
) -> "HTTPResponse":
self._onClose = callback
return self

def __str__(self) -> str:
return f"Response({self.protocol} {self.status} {self.message} {self.headers} {self.body})"

Expand Down
6 changes: 6 additions & 0 deletions src/py/extra/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,12 @@ async def SendResponse(
except Exception as e:
# NOTE: close handler failed
exception(e)
if res and res._onClose:
try:
res._onClose(res)
except Exception as e:
# NOTE: close handler failed
exception(e)
if req and not sent:
try:
warning(
Expand Down

0 comments on commit 2afd3c1

Please sign in to comment.