Django - 以编程方式构建settings.DATABASES dict

时间:2011-02-25 21:31:30

标签: django settings

我的网站大约有7个dbs(网站的国家/地区特定实例),我在设置中的DATABASES dict中有很多重复,因为对于每个条目,唯一改变的是DATABASE键。

所以我想在设置中动态构建dict。我的代码运行正常并构建了与之前手动输入相同的dict,但出于某种原因,当我尝试运行它时出现此错误:

_mysql_exceptions.OperationalError: (1046, 'No database selected')

这是我在设置中用来生成字典的代码:

DATABASES = {}

for d in DBS:
    #SITE_INSTANCE, e.g. 'dev' and DBS is a list of db names
    name = '%s_%s' % (SITE_INSTANCE, d)   

    if not DATABASES:   #first item - set up 'default'
        d = 'default'
    DATABASES[d] = {}       
    DATABASES[d]['name'] = name
    DATABASES[d]['ENGINE'] = DB_ENGINE    
    DATABASES[d]['USER'] = DB_USERNAME
    DATABASES[d]['PASSWORD'] = DB_PASSWORD

正如我所说,生成的字典与我手动输入的字典无法区分。我不明白为什么这不起作用。

2 个答案:

答案 0 :(得分:3)

您需要'NAME',而不是'name'

答案 1 :(得分:1)

以下代码提供了一些指定数据库设置的不同方法,包括允许旧的Django 1.2样式的DATABASE_FOO声明:

# Settings with no underscores in their names apply to the "default"
# database out-of-the-box
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'foo.sqlite'
DATABASE_USER = ''
DATABASE_PASSWORD = ''
DATABASE_HOST = ''
DATABASE_PORT = ''

# Since this setting has underscores in it, it needs to be specified the
# long way to disambiguate
DATABASE_default_SUPPORTS_TRANSACTIONS = True

# Specifying any settings for a database will implicitly copy everything
# else from default.
DATABASE_baz_NAME = 'baz.sqlite'

# Databases can also be defined with Django 1.2-style dicts
DATABASE_bar = {
    'NAME': 'bar.sqlite',
}

# Empty dicts will create complete clones of default
DATABASE_clone = {}

......这是实施:

databases = {}
database_global_settings = set([
    'DATABASE_ROUTERS',
])
current_settings = globals()
for (k, v) in current_settings.items():
    if k in database_global_settings:
        continue
    if k.startswith('DATABASE_'):
        if k.count('_') >= 2:
            (dummy_label, dbname, variable) = k.split('_', 2)
            if not dbname in databases:
                databases[dbname] = {}
            databases[dbname][variable] = v
        elif isinstance(v, dict):
            (dummy_label, dbname) = k.split('_', 1)
            if dbname in databases:
                databases[dbname].update(v)
            else:
                databases[dbname] = v
        else:
            # legacy configuration for default database
            dbname = 'default'
            (dummy_label, variable) = k.split('_', 1)
            if not dbname in databases:
                databases[dbname] = {}
            databases[dbname][variable] = v
        del globals()[k]
for database_name in databases:
    if database_name != 'default':
        for (k, v) in databases['default'].iteritems():
            databases[database_name].setdefault(k, v)
DATABASES = databases