LoginSignup
0
0

More than 1 year has passed since last update.

DjangoのSettings.py、DATABESESの値に MariaDBの設定を埋め込んでみた

Last updated at Posted at 2022-05-16

DjangoでRaspberryPiにインストールしたMariaDBを使いたい

Settings.pyにIDやパスワードをベタ書きにしてもよかったのだが、平文のパスワードをプログラム上に置きたくなかったのと、別のブログラムでもそれを共用していたので、Yaml形式のConfigファイルを生成し、プログラムとは別の場所に保存して使い回すことにした。

Yamlファイルの中身

以下はyaml形式のConfigファイル

#config.yaml
auth_info:
  ID: hoge_user # ここに任意のユーザー名
  password: xxxxxxx # ここに任意のパスワード
db_server:
  host: 192.168.x.x # ここにRaspberryPiのIPアドレス
  port: 3306
  db_name: db_name 
  charset: utf8mb4
  ENGINE: django.db.backends.mysql

hostであるRaspberryPiのIPアドレスははコンソール上ででip rと打ち込めばでてきます。
pyyamlが必要になるのでpip install pyyamlは必要があれば実行してください。

Configを読み出すプログラム

# config_reader.py
import yaml

def read_yaml():
    with open(r'/~任意のディレクトリ~/config.yml','r') as yaml_file:
        yml = dict(yaml.load(yaml_file, Loader=yaml.SafeLoader))
        return yml

このconfig_reader.pyをプロジェクトフォルダのutilityディレクトリに入れてSettings.pyで読み出す。

Settings.pyの途中でConfig_readerを呼び出し、Dict型データをconfig.yamlから抽出し設定に反映させる

なお、MariaDBをDjangoで使うにはmysqlclientが必要ですので、各自pip install mysqlclientは必要であれば実行してください。

# settings.pypy
"""
Django settings for stocks_db project.

Generated by 'django-admin startproject' using Django 4.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
import sys

CURRENT_DIR = str(Path(__file__).resolve().parent) + '\..'
sys.path.append(CURRENT_DIR)

import utility.config_reader

# ~ 中略 ~

yml = utility.config_reader.read_yaml()
DATABASES = {
    'default': {
        'ENGINE'   : yml['db_server']['ENGINE'],
        'NAME'     : yml['db_server']['db_name'],
        'USER'     : yml['auth_info']['ID'],
        'PASSWORD' : yml['auth_info']['password'],
        'HOST'     : yml['db_server']['host'],
        'PORT'     : yml['db_server']['port'],
    }
}

参考にした記事

DjangoでMySQLを使うためには

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0