Documentation
Overview
md.http.server.lifecycle component provides psr.http.server contract implementation to build generic high-level web-application.
Implementation defines the Mediator architecture design of high-level application how request will be handled.
Application does not manage low-level th
Consider to look for md.http.server component that provides low-level application.
Architecture overview
Lifecycle overview
Install
Usage
import psr.http.message
import md.event
import md.log
import md.http.server.lifecycle
class HandleRequest:
def on_request(self, event: md.http.server.lifecycle.RequestEvent) -> None:
# todo implement your logic here
# for example, match route, invoke and get response ...
# set response in request event
event.response = ...
assert isinstance(event.response, psr.http.message.ResponseInterface)
class HandleResponse:
def on_response(self, event: md.http.server.lifecycle.ResponseEvent) -> None:
# todo modify response
# for example, convert string to response,
# or set 404 response if there is no response
event.response = ...
assert isinstance(event.response, psr.http.message.ResponseInterface)
if __name__ == '__main__':
# arrange
event_dispatcher = md.event.Dispatcher()
logger = md.log.Logger(
keep_list=[md.log.KeepStream.from_file(filename_list=['/dev/stderr'])]
)
application = md.http.server.lifecycle.Application(
event_dispatcher=event_dispatcher,
logger=logger,
)
# act
hrq = HandleRequest()
hrs = HandleResponse()
event_dispatcher.subscribe(event=md.http.server.lifecycle.RequestEvent, handler=hrq.on_request)
event_dispatcher.subscribe(event=md.http.server.lifecycle.ResponseEvent, handler=hrs.on_response)
request = ...
assert isinstance(request, psr.http.message.RequestInterface)
response = application.handle(request=request)
Request event
md.http.server.lifecycle.RequestEvent
is an event object which is dispatched on
application request processing start.
Event object contains request
and response
attributes:
request: psr.http.message.RequestInterface
represents original request objectresponse: psr.http.message.ResponseInterface | typing.Any = None
response is to be returned by an application. Whenresponse
is type ofAny
, expected that there is someResponseEvent
event handler which finally will convert it to an instance ofpsr.http.message.ResponseInterface
.
Each handler may handle RequestEvent
without set response
value into an event object,
but when it is set, dispatcher stop dispatch cycle and returns control back to an application.
Response event
md.http.server.lifecycle.ResponseEvent
is an event object which is dispatched after
request event dispatch finished.
Event object contains request
and response
attributes:
Designed to ... or override response model.