simonw / djp

A plugin system for Django
https://djp.readthedocs.io
Apache License 2.0
90 stars 2 forks source link

Support middleware positioning relative to existing optional middleware #20

Open tomviner opened 2 weeks ago

tomviner commented 2 weeks ago

Current state of middleware hook

The instructions for Django debug toolbar say:

You should include the Debug Toolbar middleware as early as possible in the list. However, it must come after any other middleware that encodes the response’s content, such as GZipMiddleware.

This is impossible to encode in the current middleware hook, as we don't know in advance if GZipMiddleware is being used. (Same with other middleware that set REMOTE_ADDR, which Debug Toolbar uses to compare to INTERNAL_IPS)

The current workaround is just to use the settings hook, as this passes the current settings, with the current middleware. See https://github.com/tomviner/django-plugin-django-debug-toolbar/blob/3a1008184fc7e463370ba3b57a3ce2266a25780a/django_plugin_django_debug_toolbar/__init__.py#L24-L49

Proposal

The simplest way to make this possible with the middleware hook would be to pass a current_middleware arg, and respect either the return value, or edits to current_middleware if that was None

Worth also thinking if the existing Before/After/Position helpers could be made to work with optional middlewares. That is, middleware we wish to be relatively positioned to, but also, may not be present, and in that case, don't add it them.