12

我正在寻找一种方法来从命令行覆盖/定义一些单独的 django 设置,而无需额外的设置文件。

我现在需要的是在每次运行管理命令时设置 DEBUG 设置或日志记录级别。但是能够设置任何东西会很好。

4

4 回答 4

8

这是我的解决方案。将下面的代码添加到设置文件的底部。

# Process --set command line option
import sys
# This module can be imported several times,
# check if the option has been retrieved already.
if not hasattr(sys, 'arg_set'):
    # Search for the option.
    args = filter(lambda arg: arg[:6] == '--set=', sys.argv[1:])
    if len(args) > 0:
        expr = args[0][6:]
        # Remove the option from argument list, because the actual command
        # knows nothing about it.
        sys.argv.remove(args[0])
    else:
        # --set is not provided.
        expr = ''
    # Save option value for future use.
    sys.arg_set = expr
# Execute the option value.
exec sys.arg_set

然后只需将任何代码传递给任何管理命令:

./manage.py runserver --set="DEBUG=True ; TEMPLATE_DEBUG=True"
于 2011-12-20T17:10:20.787 回答
2

您可以在命令中添加自定义选项(例如日志级别)。文档

例子:

from optparse import make_option

class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--delete',
            action='store_true',
            dest='delete',
            default=False,
            help='Delete poll instead of closing it'),
        )
    # ...
于 2011-12-19T15:30:04.820 回答
2

在 settings.py 中,您可以检查命令行参数,如下所示:

import sys

# for testing
if "--enable-wiki" in sys.argv:
    ENABLE_WIKI = True
    sys.argv.remove("--enable-wiki")

用法:

./manage.py test --enable-wiki MyApp.tests
于 2020-06-21T15:18:10.620 回答
-1

您可以让您的 settings.py 更加了解它的当前环境:

DEBUG = socket.gethostname().find( 'example.com' ) == -1

以下是测试时针对不同数据库的选项:

'ENGINE': 'sqlite3' if 'test_coverage' in sys.argv else 'django.db.backends.postgresql_psycopg2',
于 2011-12-19T17:24:50.497 回答