Skip to content

Allow user provided handlers #177

@cblegare

Description

@cblegare

Hello there!

While investigating #176 I found it could be useful to add user provided handler factories to Mangum. It could look like

    def __init__(
        self, 
        app: ASGIApp, 
        lifespan: str = "auto", 
        additional_handler_factories: Optional[List[Callable[[event: dict, context: "LambdaContext", Dict[str, Any]], AbstractHandler]]] = None
        **handler_kwargs: Dict[str, Any]
    ) -> None:
        self.app = app
        self.lifespan = lifespan
        self.additional_handler_factories = additional_handle_factories or []
        self.additional_handler_factories.append(AbstractHandler.from_trigger)
        self.handler_kwargs = handler_kwargs

        if self.lifespan not in ("auto", "on", "off"):
            raise ConfigurationError(
                "Invalid argument supplied for `lifespan`. Choices are: auto|on|off"
            )


    def __call__(self, event: dict, context: "LambdaContext") -> dict:
        logger.debug("Event received.")


        with ExitStack() as stack:
            if self.lifespan != "off":
                lifespan_cycle: ContextManager = LifespanCycle(self.app, self.lifespan)
                stack.enter_context(lifespan_cycle)

            for handler_factory in self.additional_handler_factories:
                handler = handler_factory(event, context, **self.handler_kwargs)
                if handler:
                    break
            else:
                raise TypeError("Unable to determine handler from trigger event")

            http_cycle = HTTPCycle(handler.request)
            response = http_cycle(self.app, handler.body)


        return handler.transform_response(response)

In place of:

https://github.com/jordaneremieff/mangum/blob/3f312acb67aac30c07dfb305d3cd1881c59755c4/mangum/adapter.py#L47-L73

In order to accept user-provider handler factories. Would you be interested in this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions