1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Django項目連接多個數(shù)據(jù)庫配置方法

        共 9561字,需瀏覽 20分鐘

         ·

        2021-07-11 02:54


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


        Django作為Python最流行的web開發(fā)框架之一,可以方便地進(jìn)行app分離,受到廣大pythoner的喜愛。當(dāng)我們一個Django項目多個app需要連接不同數(shù)據(jù)庫時,我們該怎么配置呢?本文將以Python3+Django1.11為例,為大家詳細(xì)講解Django項目連接多個MySQL數(shù)據(jù)庫的配置步驟,其他數(shù)據(jù)庫也類似。


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

        Python3中PyMySQL代替了MySQLdb模塊,這里需要做一個簡單的配置。(1)用pip3安裝PyMySQL模塊

        pip3 install PyMySQL

        (2)在項目同名目錄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)實現(xiàn)了一個數(shù)據(jù)庫的連接,這個時候Django項目的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',
        }

        這里配置了一個數(shù)據(jù)庫路由myproject.database_router.DatabaseAppsRouter,然后對指定app指定了數(shù)據(jù)庫,'app01': 'default', 'app02': 'mysql02',。下面我們需要在唉項目同名目錄myproject/myproject下新建一個database_router.py來實現(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

        這樣我們就實現(xiàn)了不同app使用不同的數(shù)據(jù)庫了,我們可以使用python manage.py migrate --database=mysql02命令來實現(xiàn)數(shù)據(jù)庫同步(創(chuàng)建表)。


        往期推薦


        1、好可怕的搜索引擎!

        2、再見,APK, 你好,AAB !

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

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

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


        今天因為您的點贊和在看,讓我元氣滿滿!


        瀏覽 70
        點贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            大香蕉国产 | 被女同桌强行足脚交了 | 一级视频在线观看免费 | 免费黄色日本 | 夜天干天干啦天干天天爽 | 91精品久久人人妻人人爽人人 | 亚洲中文在线播放 | 日本一级裸体洗澡 | 帅哥操美女免费网站 | 伦理片中文字幕 |