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

Improve documentation on setting up middleware correctly #476

Open
Dreamsorcerer opened this issue Apr 24, 2023 · 0 comments
Open

Improve documentation on setting up middleware correctly #476

Dreamsorcerer opened this issue Apr 24, 2023 · 0 comments

Comments

@Dreamsorcerer
Copy link
Member

Dreamsorcerer commented Apr 24, 2023

We need to explain how to setup the middleware correctly so that it doesn't interfere with other middlewares.

This is the function I use in my projects:

def setup_debugtoolbar(app: web.Application) -> None:
    """Initialise debugtoolbar for app."""
    def is_error_middleware(f: _Middleware) -> bool:
        return getattr(f, "func", f) == error_middleware

    # Find the index of error_middleware (which may be a functools.partial).
    found_middleware = next(filter(is_error_middleware, app.middlewares))

    # Add debugtoolbar middleware to just before app's error handler.
    # This avoids debugtoolbar interrupting other middlewares.
    insert_pos = app.middlewares.index(found_middleware) + 1
    app.middlewares.insert(insert_pos, aiohttp_debugtoolbar.middleware)

    # setup() won't add the middleware if it's already present.
    aiohttp_debugtoolbar.setup(app, check_host=False)

Which is called after the app's normal middlewares have already been configured.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant