How to import middleware from other file, instead of code directly to

For some reasons I am not allowed to write my middlewares into the file, but I have to write them somewhere else and import it
I have tried import it like normal python classes:

from my_addon.middleware import MyCustomMiddleware

but somehow the whole app got hang when startup, without any error or warning, I don’t know what is broken

Please be more specific. What is happening here?

Import it where? If you look at your file, you’ll see the middleware listed there as quoted strings, without being imported.

Please describe your directory structure, and the location of your middleware file. Also show your MIDDLEWARE setting.

Please be more specific. What is happening here?

I am working on an open source library, I am legally allow to do anything with it, but my leader said he dont want to edit the library files too much, so I must create a new file include my custom middlewares, then import them to file

Import it where?

In the file, I import it like this:
from my_addon.middleware import MyCustomMiddleware
then I add MyCustomMiddleware to the middleware list in

No. There’s no need to do that.

If my_addon is a directory and identified in your INSTALLED_APPS setting, then you only need to add my_addon.middleware.MyCustomMiddleware to your MIDDLEWARE setting.

Middleware isn’t specifically associated with an app. It exists in a level of the stack outside the “app” structure. (They apply to every request coming in.)

1 Like

Oh right, it worked now, thank you for your help!