Django Reusable Application Configuration

时光总嘲笑我的痴心妄想 提交于 2019-12-05 19:24:46
Alasdair

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!