Skip to content

Should this become ASGI framework agnostic? Nearly there #30

@florimondmanca

Description

@florimondmanca

Hi there,

This was flagged on florimondmanca/awesome-asgi#84 as a tool providing "amazing output in the developement phase". It surely looks so!

awesome-asgi is focused on tools and libraries that are as close to the ASGI spec as possible, i.e. "framework agnostic".

StarceptionMiddleware is already a pure ASGI middleware so it's already fairly agnostic.

From a quick analysis, it seems the only bit preventing this middleware from being usable with any ASGI framework is this line:

https://github.com/alex-oleshkevich/starception/blob/master/starception/middleware.py#L42

This would notably work with Starlette, which sets scope["app"] and exposes a .debug attribute. But this is not guaranteed to work for other frameworks if they don't comply with this interface (which will almost certainly be the case).

Maybe this middleware could keep the "automatic debug detection" functionality for Starlette-based framework, and rely on a debug=... parameter for other cases? Something like this...

class StarceptionMiddleware:
    def __init__(self, app, *, debug=None):
        self.app = app
        self._debug = debug

    async def __call__(self, scope, receive, send):
        ...

        try:
            debug = request.app.debug
        except AttributeError:
            if self._debug is None:
                raise RuntimeError(
                    "Could not infer whether the app is running in debug mode, as "
                    "'request.app.debug' is unavailable. "
                    "Hint: you can pass a debug flag explicitly using "
                    "'StarceptionMiddleware(app, debug=...)'."
                )
            debug = self._debug

Then, I believe the Integration with other frameworks documentation could hint at using StarceptionMiddleware(app, debug=...) instead of hinting users at using the exception_handler.

I believe that would work better because a) most (all?) of the ASGI frameworks have some middleware mounting API, but b) most frameworks that have an error handler API won't accept a Starlette Request instance.

Then I think the library would be fully framework-agnostic! On top of allowing support for the widest userbase possible, in my experience this also reduces the maintenance burden. Starlette can be hidden as an implementation detail, and not exposed in the library public API at all.

What do you think? I'll be happy to provide a PR.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions