Django项目连接多个数据库配置
1、设置数据库连接
pip install PyMySQL
2、在项目同名目录myproject/myproject下的__init__.py添加以下代码
import pymysql
pymysql.install_as_MySQLdb()
3、修改settings.py中默认的数据库 default
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #数据库引擎
'NAME': 'pythondms', #数据库名
'USER': 'root', #用户名
'PASSWORD': '', #密码
'HOST': '36.103.245.29', #数据库主机,默认为localhost
'PORT': '3306', #数据库端口,MySQL默认为3306
'OPTIONS': {
'autocommit': True,
}
}
}
4、多数据库连接配置
#数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #数据库引擎
'NAME': 'pythondms', #数据库名
'USER': 'root', #用户名
'PASSWORD': '', #密码
'HOST': '36.103.245.29', #数据库主机,默认为localhost
'PORT': '3306', #数据库端口,MySQL默认为3306
'OPTIONS': {
'autocommit': True,
}
},
'default1': {
'ENGINE': 'django.db.backends.mysql', #数据库引擎
'NAME': 'pythondms', #数据库名
'USER': 'root', #用户名
'PASSWORD': '', #密码
'HOST': '39.107.35.95', #数据库主机,默认为localhost
'PORT': '3306', #数据库端口,MySQL默认为3306
'OPTIONS': {
'autocommit': True,
}
}
}
DATABASE_ROUTERS = ['dms.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
'userctrl': 'default',
'app02': 'default1',
}
这里配置了一个数据库路由dms.database_router.DatabaseAppsRouter,然后对指定app指定了数据库,'userctrl': 'default', 'app02': 'default',。下面我们需要在唉项目同名目录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命令来实现数据库同步(创建表)
Django项目连接多个数据库配置的更多相关文章
- 创建Django项目(二)——数据库配置
2013-08-05 20:53:44| 1.数据库配置 举例是用MySQL数据库,首先在settings文件中做配置,如下: DATABASES = { ' ...
- 搭建django项目连接mysql数据库环境
开通博客园这么久,即将写下第一篇博客,十分兴奋.首先了,庆祝自己写下了码农生涯博客园第一篇博客,其次了,庆祝自己经过了10个小时奋战,终于成功搭建django项目连接mysql数据库的环境.在此过程中 ...
- Pycharm中的Django项目连接mysql数据库
一.安装Pycharm和Django就不详细说了,自行百度 二.新建Django项目也不说了 三.配置Django连接到mysql 1.models.py写一个类,继承models.Model cla ...
- django项目settings.py的基础配置
一个新的django项目初始需要配置settings.py文件: 1. 项目路径配置 新建一个apps文件夹,把所有的项目都放在apps文件夹下,比如apps下有一个message项目,如果不进行此项 ...
- Django之连接远程mysql数据库
1.创建Django项目(test) 进入配置文件settings.py 192.168.83.129:所需要远程连接数据库的ip地址 2.进入到远程连接的主机,修改/etc/mysql/mysql. ...
- Web框架之Django_01初识(三大主流web框架、Django安装、Django项目创建方式及其相关配置、Django基础三件套:HttpResponse、render、redirect)
摘要: Web框架概述 Django简介 Django项目创建 Django基础必备三件套(HttpResponse.render.redirect) 一.Web框架概述: Python三大主流Web ...
- django和flask关于oralce数据库配置
Django中关于Oracle数据库配置 # 使用SERVICE_NAME DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracl ...
- django 项目中使用多数据库 multiple databases
假如在一个django项目中使用到了不只一个数据库, 其实这在大一点的工程中很常见,比如主从库 那么会涉及到如下一些东西 1, 定义 在settings中的DATABASE中定义会使用到的数据,比如除 ...
- Django项目发布到Apache2.4配置mod_wsgi,解决遭遇的各种坑。
环境: Apache2.4 32bit Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:05:16) [MSC v.1915 32 bit (Inte ...
随机推荐
- 鸿蒙OS的系统调用是如何实现的? | 解读鸿蒙源码
本文将首先带您回顾"系统调用"的概念以及它的作用,然后从经典的Hello World开始,逐行代码层层分析--鸿蒙OS的系统调用是如何实现的. 写在前面 9月10号 华为开发者大会 ...
- 使用axios实现登录功能
1.创建一个login.vue页面 1.1写页面components/Login.vue 在 src/components 下创建 Login.vue 页面 <template> < ...
- 16个非常有趣的HTML5 Canvas动画特效集合
HTML5技术正在不断的发展和更新,越来越多的开发者也正在加入HTML5阵营,甚至在移动开发上HTML5的地位也是越来越重要了.HTML5中的大部分动画都是通过Canvas实现,因为Canvas就像一 ...
- sentinel整合servlet
<dependency> <groupId>com.alibaba.csp</groupId> <artifactId>sentinel-web-ser ...
- 【mq读书笔记】消息过滤机制
mq支持表达式过滤和类过滤两种模式,其中表达式又分为TAG和SQL92.类过滤模式允许提交一个过滤类到FilterServer,消息消费者从FilterServer拉取消息,消息经过FilterSer ...
- [Docker]Docker与Linux ip_forward数据包转发
背景 今天在一台新虚拟机上需要临时启动一个consul服务,安装Docker后使用docker启动,但是在执行启动命令后发现docker有一个警告: WARNING: IPv4 forwarding ...
- 下载配置VNC
VNC通常使用连接图形化系统电脑可以安装了Gnome或者KDE yum autoremo ve tigervnc-server //移除 vncreboot //重启yum install tiger ...
- flask实现分类搜索的小测试
最新学长要求实现一个搜索的功能呢,也费了一点功夫.这个案例也没有学长写的好,比学长的实现差了不少,待我仔细研究习再发出相应代码 项目要求,搜索语法如下: titile: xxx #搜索titile的所 ...
- Java基础学习之流程控制语句(5)
目录 1.顺序结构 2.选择结构 2.1.if else结构 2.2.switch case结构 3.循环结构 3.1.while结构 3.2.do while结构 3.3.for结构 3.3.1.普 ...
- js 面试题正则相关
正则相关[i不区分大小写,g匹配全部数据] var str = "Hello word! I think word is good."; 1.替换str中的word为javascr ...