I'm aware I can "store it anywhere in my python path" and all, but what's an organized pattern I can use to store middleware classes for my project?
I am appending my project root directory and project directory to the sys path through mod_wsgi:
sys.path.append( '/srv/' )
sys.path.append( '/srv/workarounds/' )
The latter line being the project root. As an example, let's say I want to apply this middleware class: http://djangosnippets.org/snippets/1179/
Would I just copy the snippet contents into a middleware.py file and dump it in my project root? Create a directory for middleware, add that directory to my python path?
Each middleware component is responsible for doing some specific function. For example, Django includes a middleware component, AuthenticationMiddleware , that associates users with requests using sessions.
How do you determine at startup time if a piece of middleware should be used? Raise MiddlewareNotUsed in the init function of your middleware. Implement the not_used method in your middleware class. List the middleware beneath an entry of django.
Middleware and decorators are similar and can do the same job. They provide a means of inserting intermediary effects either before or after other effects downstream in the chain/stack.
An app name is just the name of the Python module. Nothing more. A python module name is the case name of the root folder of the module, that must contains an init.py file. If you want to know what this name is, go to your site-packages folder and look for your module.
If you have only a couple of tightly coupled middleware classes put them into a middleware.py
module under the app root. (This is how the django.contrib
apps do it - see the sessions' app middleware here).
If you have many varying middleware classes, create a middleware pacakge with submodules of the related middleware classes. Though if you do end up in this situation, consider how you can refactor your project into several mini-apps that all solve a specific need (and open source them :)).
Personally, I have a common django package where I dump common middleware (like the your linked LoginRequiredMiddleware
class) into a middleware
package. If this makes sense in your project's context I would highly suggest it. It's saved my countless hours of duplication, and bug fixing. django-common and django-annoying are good examples of this kind of project layout
My usual layout for a django site is:
projects/
templates/
common/
local/
Where:
I generally put middleware that's project-specific inside a project, and middleware that's not project-specific in common/middleware/
Make sure to add the templates directory to the right place in settings (or most probably, localconfig.py and then import it in settings), and makse sure to add the projects, common, and local directories to your PYTHONPATH.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With