Skip to content

fix: keep the parent's child container when a sub-app also calls setup_di - #47

Merged
lesnik512 merged 1 commit into
mainfrom
fix/nested-setup-di-subapp
Oct 17, 2026
Merged

lesnik512 merged 1 commit into
mainfrom
fix/nested-setup-di-subapp

Conversation

@lesnik512

Copy link
Copy Markdown
Member

Closes #45

When the parent app and a sub-app both call setup_di, both middlewares store the child container under the same request key. On a sub-app route the inner middleware deleted the key on exit, and the outer middleware's unconditional del then raised KeyError, so the response became a 500.

The middleware now reads the key's previous value before setting its own. On exit it puts that value back, or deletes the key when there was none. Deleting in the outermost middleware still breaks the request/container reference cycle, so the existing no-cyclic-garbage test is unchanged. A sub-app route resolves from the innermost app's container, and each middleware still closes the child container it opened.

Tests in tests/test_subapps.py:

  • With setup_di on both apps, /x returns the parent's value and /sub/x returns the sub-app's, both 200.
  • With setup_di on the parent only, /sub/x resolves from the parent's container. This one already passed before the fix and guards against a regression.
  • A sub-app request runs the finalizers of both child containers. A test middleware on the parent resolves a cached request-scoped dependency from the parent's child container so it has something to finalize.

The first and third tests fail on main with the KeyError.

The README now says which container a sub-app route resolves from in each setup.

@lesnik512
lesnik512 merged commit cab2cbb into main Oct 17, 2026
12 checks passed
@lesnik512
lesnik512 deleted the fix/nested-setup-di-subapp branch October 17, 2026 09:59
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

Successfully merging this pull request may close these issues.

setup_di on both a parent app and a sub-app returns 500 for every sub-app route

1 participant