やりたいこと
django のプログラムで接続先の DB の情報を確認する。
接続先の DB の情報は django.db の connection で参照することができる。
from django.db import connection
connection.settings_dict
プログラム例
プログラム構成
以下の記事と同じプログラム構成で接続先 DB の情報を取得する API を追加する。
pytest による django の Web API のテスト自動化
app1/services.py: 接続先のDB情報
django.db の connection を import すると、connection.settings_dict で接続先の DB を参照することができる。
app1/services.py
from django.db import connection
def get_db_info():
db_info = connection.settings_dict
return db_info
app1/views.py
app1/services.py の get_db_info の実行結果を返却する API を定義する。
app1/views.py
from app1.services import (
...,
get_db_info,
)
@csrf_exempt
@require_http_methods(["GET"])
def api_get_db_info(request):
response = {
'data': None,
}
response['data'] = get_db_info()
return JsonResponse(response)
pytest1/urls.py
ここでは API の URL を /app1/db/ とする。
pytest1/urls.py
from app1.views import (
...,
api_get_db_info,
)
urlpatterns = [
...,
path('app1/db/', api_get_db_info),
]
実行例
API で DB のホスト、ポート番号、スキーマ名、データベース名、ユーザ名などを取得することができる。
※パスワードも含まれることに注意
$ curl http://127.0.0.1:8000/app1/db/ | jq
{
"data": {
"ENGINE": "tenant_schemas.postgresql_backend",
"NAME": "pytest1",
"USER": "...",
"PASSWORD": "...",
"HOST": "localhost",
"PORT": "5432",
"ATOMIC_REQUESTS": false,
"AUTOCOMMIT": true,
"CONN_MAX_AGE": 0,
"CONN_HEALTH_CHECKS": false,
"OPTIONS": {},
"TIME_ZONE": null,
"TEST": {
"CHARSET": null,
"COLLATION": null,
"MIGRATE": true,
"MIRROR": null,
"NAME": null
},
"SCHEMA": "public"
}
}