Django作為Python最流行的web開發(fā)框架之一卦尊,可以方便地進(jìn)行app分離堡掏,受到廣大pythoner的喜愛呻纹。當(dāng)我們一個(gè)Django項(xiàng)目多個(gè)app需要連接不同數(shù)據(jù)庫時(shí)宋梧,我們該怎么配置呢匣沼?本文將以Python3+Django1.11為例,為大家詳細(xì)講解Django項(xiàng)目連接多個(gè)MySQL數(shù)據(jù)庫的配置步驟捂龄,其他數(shù)據(jù)庫也類似释涛。
1、設(shè)置數(shù)據(jù)庫連接
Python3中PyMySQL代替了MySQLdb模塊倦沧,這里需要做一個(gè)簡單的配置唇撬。
(1)用pip3安裝PyMySQL模塊
pip3 install PyMySQL
(2)在項(xiàng)目同名目錄myproject/myproject
下的__init__.py
添加以下代碼
import pymysql
pymysql.install_as_MySQLdb()
(3) 修改settings.py
中默認(rèn)的數(shù)據(jù)庫 default
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql01', #連接的數(shù)據(jù)庫名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
}
}
至此,默認(rèn)數(shù)據(jù)庫連接配置完成展融。
2窖认、多數(shù)據(jù)庫連接配置
第1步已經(jīng)實(shí)現(xiàn)了一個(gè)數(shù)據(jù)庫的連接,這個(gè)時(shí)候Django項(xiàng)目的app都使用的默認(rèn)數(shù)據(jù)庫mysql01告希,但是很多情況我們不同的app需要用不同的數(shù)據(jù)庫扑浸。
我們需要在setting.py
中進(jìn)行配置。
DATABASES = {
# 'default': {
# 'ENGINE': 'django.db.backends.sqlite3',
# 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
# }
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql01', #連接的數(shù)據(jù)庫名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
}燕偶,
'mysql02': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysql02', #連接的數(shù)據(jù)庫名
'HOST': 'localhost',
'PORT': '3306',
'USER': 'root',
'PASSWORD': 'mysql2018',
}
}
DATABASE_ROUTERS = ['myproject.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'app01': 'default',
'app02': 'mysql02',
}
這里配置了一個(gè)數(shù)據(jù)庫路由myproject.database_router.DatabaseAppsRouter
喝噪,然后對指定app指定了數(shù)據(jù)庫,'app01': 'default', 'app02': 'mysql02',
杭跪。下面我們需要在唉項(xiàng)目同名目錄myproject/myproject
下新建一個(gè)database_router.py
來實(shí)現(xiàn)數(shù)據(jù)庫路由。
# 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
這樣我們就實(shí)現(xiàn)了不同app使用不同的數(shù)據(jù)庫了驰吓,我們可以使用python manage.py migrate --database=mysql02
命令來實(shí)現(xiàn)數(shù)據(jù)庫同步(創(chuàng)建表)涧尿。
如果你喜歡本文章,還請點(diǎn)個(gè)關(guān)注和喜歡檬贰,我會(huì)為大家不斷地帶來Python學(xué)習(xí)筆記姑廉。