Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

Django的MySQL Driver配置

$
0
0

/MariaDB支持》,现在Django对mysql的支持已经很好了,现在就说一说最佳实践吧。

PEP 249 规定了python的数据库API。MySQL主要有三种API实现:

MySQLdb 是Andy Dustman开发的、使用原生代码/C语言绑定的驱动,它已经开发了数十年。 mysqlclient 是MySQLdb的一个支持Python3的fork,并且可以无缝替换调MySQLdb。mysqlclient目前是MySQL在Django下的推荐选择。 MySQL Connector/Python 是Oracle写的,纯Python实现的客户端库。

以上所有的驱动都是线程安全的,且提供了连接池。 MySQLdb 是唯一一个不支持Python3的。

如果你使用mysqlclient

settings.py中的配置如下:

# Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', #数据库引擎 'NAME': 'test',#数据库名 'USER': 'root',#用户名 'PASSWORD': 'root',#密码 'HOST': '',#数据库主机,默认为localhost 'PORT': '',#数据库端口,MySQL默认为3306 'OPTIONS': { 'autocommit': True, 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } }

第14行主要是为了防止警告:

(mysql.W002) MySQLStrictModeis not setfor databaseconnection 'default'

当然,要在requirements.txt中添加对 mysqlclient 的依赖:

mysqlclient==1.3.10

然后运行 python manage .py migrate :

$ pythonmanage.py migrate Operationsto perform: Applyallmigrations: admin, auth, contenttypes, sessions Runningmigrations: Applyingcontenttypes.0001_initial... OK 。。。。。。 如果你使用MySQL Connector/Python

这么长时间了,Oracle官方的connector还是不太好用。

首先,一些补丁需要打: patch 93c7b38 , patch 8dab00b 要打上。

其次, 这个包无法从PyPI安装了 ,只能从下载链接安装。

如果你要使用MySQL Connector/Python,首先,在requirements.txt中声明依赖:

https://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-2.1.5.tar.gz#egg=mysql-connector-python

其次,在settings.py里面关于数据库的配置如下:

# Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django',#数据库引擎 'NAME': 'test',#数据库名 'USER': 'root',#用户名 'PASSWORD': 'root',#密码 'HOST': 'localhost', 'OPTIONS': { 'autocommit': True, }, } }

然后运行 python manage .py migrate 。


Viewing all articles
Browse latest Browse all 9596

Trending Articles