liujiacai

原文:https://zhuanlan.zhihu.com/p/105717817

 

Django配置数据库有两种方法

方法一:直接在settings.py文件中添加数据库配置信息

DATABASES = {
    # 方法一
    \'default\': {
        \'ENGINE\': \'django.db.backends.mysql\',   # 数据库引擎
        \'NAME\': \'mysite\',                       # 数据库名称
        \'USER\': \'xiaohong\',                      # 数据库登录用户名
        \'PASSWORD\': \'xiaohong\',                # 密码
        \'HOST\': \'127.0.0.1\',                # 数据库主机IP,如保持默认,则为127.0.0.1
        \'PORT\': 3306,                           # 数据库端口号,如保持默认,则为3306
    }
}

方法二:将数据库配置信息存到一个文件中,在settings.py文件中将其引入。(推荐)

新建数据库配置文件my.cnf(名字随意选择)

[client]
database = blog
user = blog
password = blog
host =127.0.0.1
port = 3306
default-character-set = utf8

在settings.py文件中引入my.cnf文件

DATABASES = {
    # 方法二:
    \'default\': {
        \'ENGINE\': \'django.db.backends.mysql\',
        \'OPTIONS\': {
            \'read_default_file\': \'utils/dbs/my.cnf\',
        },
    }
}

启用Django与mysql的连接

在生产环境中安装pymysql并且需要在settings.py文件所在包中的__init__.py中导入pymysql

import pymysql

pymysql.install_as_MySQLdb()

到此mysql数据库配置完成

如果还报错:

pymysql报错:cryptography is required for sha256_password or caching_sha2_password

这段报错意思是说 sha256_password 和 caching_sha2_password 这两个加密算法需要用到 cryptography 。虽然意思很明了,但是可能不知道如何解决。
其实 cryptography 是一个python包,所以解决方法很简单:

$ pip install cryptography
完事。

分类:

技术点:

相关文章: