Skip to content

Middleware stacking and recursive initialization #2002

@Kludex

Description

@Kludex

Discussed in #1161

Originally posted by euri10 April 1, 2021
long story short I was writing a logging middleware whose handlers are initialized in the __init__ of the middleware and ended up with multiple logs.

it seems to me the __init__ of the middlewarea are recursively called because of the build_middleware_stack method and I'm not sure if this is intended or a bug.

here's a test case that shows what I think is an issue:

class SimpleInitializableMiddleware:
    def __init__(self, app, counter: int):
        self.app = app
        self.counter = counter
        print(self.counter)


def test_middleware_stack_init():
    app = Starlette()
    app.add_middleware(SimpleInitializableMiddleware, counter=1)
    app.add_middleware(SimpleInitializableMiddleware, counter=2)
    app.add_middleware(SimpleInitializableMiddleware, counter=3)
    app.add_middleware(SimpleInitializableMiddleware, counter=4)

I would expect to see 1 2 3 4 as the output.
however it prints 1 1 2 1 2 3 1 2 3 4 because for each add_middlware call it goes down the stack and reinitialize it.

what you think @tomchristie ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    clean upRefinement to existing functionality

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions