I have some Django middleware code that connects to a database. I want to turn the middleware into a reusable application ("app") so I can package it for distribution into many other projects, without needing to copy-and-paste.
I don't understand where a reusable application is supposed to configure itself. Since it's intended for redistribution I don't have the ability to write the central settings.py myself. Looking at the Django documentation I see there's settings.configure but it appears to replace the entire configuration, instead of letting me "splice" a new database into DATABASES.
What's the right way to give my reusable middleware app the ability to configure its own database connection? I don't want it to interfere with the databases of applications where I'll be installing it. Thanks.
You could follow the approach of Django debug toolbar. It includes an app config class, and overrides the settings in the ready
method.
You can see the code here.
Database Connection.
Well first of all I am not quite sure it's a good idea for a middleware to connect to anything other than the default database for the project. If you really want that feature it would be best to ask the user to add it to the settings file directly because the database connection settings will vary wildly from install to install.
If your app wants to make raw queries just do
from django.db import connection
cursor = connection.cursor()
It would be better to use the ORM if you can.
App specific settings
One method is to create a file called app_settings.py in your reusable app. Then you can add code like the following into it.
from django.conf import settings
SOME_APP_SETTING = getattr(settings, 'SOME_APP_SETTING', SOME_DEFAULT)
This allows anyone installing your app to change some of the settings in the main settings.py file.
If you really wanted to get fancy, you could create a custom database settings section here and allow the user to override it in the settings.py file.