Django项目连接多个数据库配置方法
作者:橙子丨Sunty 链接:https://www.jianshu.com/p/1d4442b683e6
Django作为Python最流行的web开发框架之一,可以方便地进行app分离,受到广大pythoner的喜爱。当我们一个Django项目多个app需要连接不同数据库时,我们该怎么配置呢?本文将以Python3+Django1.11为例,为大家详细讲解Django项目连接多个MySQL数据库的配置步骤,其他数据库也类似。
1、设置数据库连接
Python3中PyMySQL代替了MySQLdb模块,这里需要做一个简单的配置。(1)用pip3安装PyMySQL模块
pip3 install PyMySQL
(2)在项目同名目录myproject/myproject
下的__init__.py
添加以下代码
import pymysql
pymysql.install_as_MySQLdb()
(3) 修改settings.py
中默认的数据库 default
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql01', #连接的数据库名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
}
}
至此,默认数据库连接配置完成。
2、多数据库连接配置
第1步已经实现了一个数据库的连接,这个时候Django项目的app都使用的默认数据库mysql01
,但是很多情况我们不同的app需要用不同的数据库。我们需要在setting.py
中进行配置。
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql01', #连接的数据库名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
},
'mysql02': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql02', #连接的数据库名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
}
}
DATABASE_ROUTERS = ['myproject.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'app01': 'default',
'app02': 'mysql02',
}
这里配置了一个数据库路由myproject.database_router.DatabaseAppsRouter
,然后对指定app指定了数据库,'app01': 'default', 'app02': 'mysql02',
。下面我们需要在唉项目同名目录myproject/myproject
下新建一个database_router.py
来实现数据库路由。
# database_router.py
from django.conf import settings
DATABASE_MAPPING = settings.DATABASE_APPS_MAPPING
class DatabaseAppsRouter(object):
"""
A router to control all database operations on models for different
databases.
In case an app is not set in settings.DATABASE_APPS_MAPPING, the router
will fallback to the `default` database.
Settings example:
DATABASE_APPS_MAPPING = {'app1': 'db1', 'app2': 'db2'}
"""
def db_for_read(self, model, **hints):
""""Point all read operations to the specific database."""
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def db_for_write(self, model, **hints):
"""Point all write operations to the specific database."""
if model._meta.app_label in DATABASE_MAPPING:
return DATABASE_MAPPING[model._meta.app_label]
return None
def allow_relation(self, obj1, obj2, **hints):
"""Allow any relation between apps that use the same database."""
db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label)
db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label)
if db_obj1 and db_obj2:
if db_obj1 == db_obj2:
return True
else:
return False
return None
def allow_syncdb(self, db, model):
"""Make sure that apps only appear in the related database."""
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(model._meta.app_label) == db
elif model._meta.app_label in DATABASE_MAPPING:
return False
return None
def allow_migrate(self, db, app_label, model=None, **hints):
"""
Make sure the auth app only appears in the 'auth_db'
database.
"""
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(app_label) == db
elif app_label in DATABASE_MAPPING:
return False
return None
# for Django 1.4 - Django 1.6
def allow_syncdb(self, db, model):
"""Make sure that apps only appear in the related database."""
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(model._meta.app_label) == db
elif model._meta.app_label in DATABASE_MAPPING:
return False
return None
# Django 1.7 - Django 1.11
def allow_migrate(self, db, app_label, model_name=None, **hints):
print db, app_label, model_name, hints
if db in DATABASE_MAPPING.values():
return DATABASE_MAPPING.get(app_label) == db
elif app_label in DATABASE_MAPPING:
return False
return None
这样我们就实现了不同app使用不同的数据库了,我们可以使用python manage.py migrate --database=mysql02
命令来实现数据库同步(创建表)。
5、微软:不是所有电脑都能升级Win11,网友:看我偷梁换柱
今天因为您的点赞和在看,让我元气满满!