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?
My usual layout for a django site is:
projects/
templates/
common/
local/
Where:
- projects contains your main project and any others
- common contains things you may share across sites, or are at least not project-specific, like if you need to download django-profile and django-registration rather than having it directly in python/site-packages
- templates contains just that
- local contains things that are going to be specific to the current machine, so that you can have properly separated data, like database location and password - I then soft-link the machine-specific versions (say "machine1-localconfig.py") to local/localconfig.py and then can "import localconfig" in settings.py
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 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