Django 資料庫配置(二)
動態連線資料庫
動態連線資料庫是為了在系統不中斷的情況下切換到另一個數據庫,因為在settings.py中配置資料庫時,每次儲存都會自動重啟Django,在有使用者正在使用時,這種操作會導致使用者的資料丟失,為避免這種情況。可以將資料庫的連線方式寫到配置檔案中,這樣無需修改settings.py的配置就可以切換資料庫的目的。
首先在專案目錄下,建立配置檔案mysql.cnf,然後在配置檔案mysql.cnf中寫入mysql資料庫的連線資訊,程式碼如下:
#mysql 資料庫連結配置 [client] database = accent user = root password = root@123host = 192.168.129.130 port = 3306 database = manage user = root password = root@123 host = 192.168.129.130 port = 3306
在Django的settings.py配置檔案中,修改資料庫連線讀取配置檔案的資訊,程式碼如下:
DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # } #讀取資料庫配置檔案中的資料庫連線資訊"default":{ "ENGINE":"django.db.backends.mysql", "OPTIONS":{"read_default_file":str(BASE_DIR / "mysql.cnf")}, } }
驗證mysql.cnf配置檔案是否能訪問資料庫,在專案的urls.py中設定路由index,且路由檢視函式indexView(),程式碼如下:
from django.contrib import admin from django.urls import path,re_path from myapp.views import index urlpatterns= [ path('admin/', admin.site.urls), path("",index), ]
在檢視中讀取資料庫資訊,並列印到頁面上:
from django.shortcuts import render from django.contrib.contenttypes.models import ContentType # Create your views here. def index(request): c = ContentType.objects.values_list().all() content = {} content["dbinfo"] = c return render(request,"index.html",content)
修改index.html模板內容,顯示資料庫資訊
<html lang="en"> <head> <mete charset="utf-8"></mete> <title>hello word</title> </head> <body> <p>{{dbinfo}}</p> </body> </html>
啟動Django之前,需要新建立資料庫表,在專案路徑下,執行以下命令:
python manage.py migrate
啟動Django服務:
python manage.py runserver 8000
在瀏覽器中訪問伺服器地址:https://127.0.0.1:8000
問題:在python manage.py migrate 時會報django.db.utils.OperationalError: (1045, "Access denied for user 'Administrator'@'localhost' (using password: NO)")
將資料庫配置資訊打印出來,引數配置沒有問題,但是貌似沒有讀取資料庫配置檔案的內容,如下:
解決方式:後面網上找到一篇帖子:https://code.djangoproject.com/ticket/24653
在settings.py配置檔案中,匯入io模組,在資料庫配置中引入io路徑拼接,如下:
再將DATABASES改為:
"default":{ "ENGINE":"django.db.backends.mysql", "OPTIONS":{"read_default_file":os.path.join(BASE_DIR / "MyDjango/mysql.cnf")}, }
再次執行python mange.py migrate 就能建立資料庫成功。