六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 223|回复: 0

settings.py 中设置访问 数据库

[复制链接]

升级  34%

21

主题

21

主题

21

主题

秀才

Rank: 2

积分
101
 楼主| 发表于 2013-1-30 01:30:08 | 显示全部楼层 |阅读模式
Django访问数据库的设置是在settings.py中写入数据库的engine、用户名和密码,默认的写法是:

DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
DATABASE_NAME = 'xxx' # Or path to database file if using sqlite3.
DATABASE_USER = 'root' # Not used with sqlite3.
DATABASE_PASSWORD = 'xxx' # Not used with sqlite3.
DATABASE_HOST = 'localhost' # Set to empty string for localhost. Not used with sqlite3.
DATABASE_PORT = '3306' # Set to empty string for default. Not used with sqlite3.

数据库的关键信息都写在settings.py中,这样做是非常不安全的。现在可以在settings.py里面使用DATABASE项代替以上的配置项,username和password可以写在配置文件中。下面是把username和password放到MySQL数据库的配置文件中,由 DATABASE项读取的示例:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/etc/mysql/my.cnf',
        },
    }
}

# my.cnf
[client]
database = xxx
user = xxx
password = xxxxxx
default-character-set = utf8

也可以在DATABASES中加入NAME来指定数据库名,client中去除database选项,HOST和PORT这些也都可以写在my.cnf文件中。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表