<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Django項(xiàng)目連接多個(gè)數(shù)據(jù)庫(kù)配置方法

          共 9561字,需瀏覽 20分鐘

           ·

          2021-07-11 02:54


          作者:橙子丨Sunty 鏈接:https://www.jianshu.com/p/1d4442b683e6


          Django作為Python最流行的web開發(fā)框架之一,可以方便地進(jìn)行app分離,受到廣大pythoner的喜愛(ài)。當(dāng)我們一個(gè)Django項(xiàng)目多個(gè)app需要連接不同數(shù)據(jù)庫(kù)時(shí),我們?cè)撛趺磁渲媚兀勘疚膶⒁訮ython3+Django1.11為例,為大家詳細(xì)講解Django項(xiàng)目連接多個(gè)MySQL數(shù)據(jù)庫(kù)的配置步驟,其他數(shù)據(jù)庫(kù)也類似。


          1、設(shè)置數(shù)據(jù)庫(kù)連接

          Python3中PyMySQL代替了MySQLdb模塊,這里需要做一個(gè)簡(jiǎn)單的配置。(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ù)庫(kù) 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ù)庫(kù)名
                  'HOST''localhost',
                  'PORT''3306',
                  'USER''root',
                  'PASSWORD''mysql2018',
              }
          }

          至此,默認(rèn)數(shù)據(jù)庫(kù)連接配置完成。

          2、多數(shù)據(jù)庫(kù)連接配置

          第1步已經(jīng)實(shí)現(xiàn)了一個(gè)數(shù)據(jù)庫(kù)的連接,這個(gè)時(shí)候Django項(xiàng)目的app都使用的默認(rèn)數(shù)據(jù)庫(kù)mysql01,但是很多情況我們不同的app需要用不同的數(shù)據(jù)庫(kù)。我們需要在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ù)庫(kù)名
                  'HOST''localhost',
                  'PORT''3306',
                  'USER''root',
                  'PASSWORD''mysql2018',
              },
              'mysql02': {
                  'ENGINE''django.db.backends.mysql',
                  'NAME''mysql02'#連接的數(shù)據(jù)庫(kù)名
                  'HOST''localhost',
                  'PORT''3306',
                  'USER''root',
                  'PASSWORD''mysql2018',
              }
          }

          DATABASE_ROUTERS = ['myproject.database_router.DatabaseAppsRouter']
          DATABASE_APPS_MAPPING = {
              'app01''default',
              'app02''mysql02',
          }

          這里配置了一個(gè)數(shù)據(jù)庫(kù)路由myproject.database_router.DatabaseAppsRouter,然后對(duì)指定app指定了數(shù)據(jù)庫(kù),'app01': 'default', 'app02': 'mysql02',。下面我們需要在唉項(xiàng)目同名目錄myproject/myproject下新建一個(gè)database_router.py來(lái)實(shí)現(xiàn)數(shù)據(jù)庫(kù)路由。

          # 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ù)庫(kù)了,我們可以使用python manage.py migrate --database=mysql02命令來(lái)實(shí)現(xiàn)數(shù)據(jù)庫(kù)同步(創(chuàng)建表)。


          往期推薦


          1、好可怕的搜索引擎!

          2、再見(jiàn),APK, 你好,AAB !

          3、什么?VS Code 里面還能找女朋友?

          4、國(guó)內(nèi)大神成功給手機(jī)裝上了Win11,支持一加、小米

          5、微軟:不是所有電腦都能升級(jí)Win11,網(wǎng)友:看我偷梁換柱


          今天因?yàn)槟狞c(diǎn)贊和在看,讓我元?dú)鉂M滿!


          瀏覽 70
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  欧美日韩精品久久久免费观看 | 精品国产乱药久久久久久 | 日韩无码第四页 | 日本色图15p | 国产黄色片在线免费观看 |