`
lbxhappy
  • 浏览: 302745 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

settings.py 中设置访问 数据库

阅读更多
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文件中。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics