用于定义外部django配置的实用程序(用于最终用户)
django-configure的Python项目详细描述
(适用于django>;=1.9及更低版本,但未经测试,请自行决定使用)
这是一个出于个人需要而建的简单图书馆。
尽管django是一个框架,但它没有为 使用最终用户配置文件扩展settings.py。只是为了确保-我不把python文件当作 设置-让最终用户能够在应用程序上下文中运行任意代码 给整个系统带来灾难的方法。
另一方面,settings.py包含了很多代码和设置,这些代码和设置并没有真正启动 对于配置(中间件、已安装的应用程序,这显然是针对开发人员的)。
对于一些越来越小的项目,我现在不得不手工编写一些代码 负责读取外部配置文件(通常是.ini样式)并将它们插入 在某些情况下,还需要一些生成存根配置的代码。
所以在某个时候我决定-“为什么我不把它变成一个可重用的应用程序呢?“-这就是 这个图书馆是造的。
此库的主要目的是让您以声明的方式指定最终用户配置:
config = django_configure.define({ 'Common': { 'secret': django_configure.type.String('Secret for the application', default=generate_secret()), 'static_root': django_configure.type.Path('Static root path (static files will be copied here)', default='/var/lib/myapp/static/'), 'static_url': django_configure.type.Path('Url to static files', default='/static/'), 'media_root': django_configure.type.Path('Media root path (media files will be stored here)', default='/var/lib/myapp/media/'), 'media_url': django_configure.type.Path('Url to media files', '/media/'), 'debug': django_configure.type.Boolean(help='if true debug mode will be enabled for the application, do not switch this in production', default=False) }, 'Database': { 'url': django_configure.type.Database('Url to access database (including credentials)', default='sqlite:////var/lib/myapp/myapp.sqlite') } }, env_prefix='MYAPP')
之后,您可以按如下方式为设置变量赋值:
SECRET_KEY=config.get('Common.secret')
由于配置文件中的字段可以识别类型,因此它们在将字符串转换为布尔值或数字方面做得很好:
DEBUG=config.get('Common.debug')
为了方便起见,生成默认配置的函数:
config = django_configure.default('myapp', env_prefix='MYAPP')
上面的代码将生成带有以下字段的config对象(secret将自动生成):
{ 'Common': { 'secret': django_configure.type.String('Secret for the application', default=generate_secret()), 'static_root': django_configure.type.Path('Static root path (static files will be copied here)', default='/var/lib/' + app_name + '/static/'), 'static_url': django_configure.type.Path('Url to static files', default='/static/'), 'media_root': django_configure.type.Path('Media root path (media files will be stored here)', default='/var/lib/' + app_name + '/media/'), 'media_url': django_configure.type.Path('Url to media files', '/media/'), 'debug': django_configure.type.Boolean(help='if true debug mode will be enabled for the application, do not switch this in production', default=False) }, 'Database': { 'url': django_configure.type.Database('Url to access database (including credentials)', default='sqlite:////var/lib/'+app_name+'/'+app_name+'.sqlite') } }
您可以通过config.append(additional_field):
config = django_configure.default('myapp', env_prefix='MYAPP') config.append({'Common': {'media_root': '/my/secret/storage'}})
在这种情况下,可以从环境变量(env_prefix+config)中读取如下指定的配置 上面的代码将是myapp_config)。配置路径也可以在配置定义中通过 默认路径变量,但不建议这样做,因为它将路径硬编码为settings.py 我们要避免的。
在settings.py中定义配置之后,可以生成模板配置和wsgi文件 通过运行manage.py命令:
python manage.py createconfig <config_path> <wsgi_path>
配置文件的路径将硬编码到wsgi文件中,因此请注意(您始终可以手动编辑 wsgi文件(稍后)
更改日志
- version 0.3.0:添加了对python 3+的支持,在配置默认值中添加了主机名。