settings ファイルの構成方法
アプリケーションの動作や起動に必要な種々のパラメータやオプションを設定・管理するために、設定ファイルが利用されます。一般的な設定ファイルの設定手順を以下に示します。
- 本アプリケーションのメインディレクトリ(通常)に「settings.py」という新しいファイルを作成する。
- 必要なモジュールをインポートします。
import os
import logging
import datetime
- グローバル変数と定数を定義する。
DEBUG = True
LOG_FILE = 'app.log'
DATABASE_HOST = 'localhost'
DATABASE_PORT = 5432
- 設定の構成を行う。
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_PATH = os.path.join(BASE_DIR, 'logs')
logging.basicConfig(filename=os.path.join(LOG_PATH, LOG_FILE), level=logging.DEBUG)
- 関数やクラスを設定する。
class AppConfig:
def __init__(self, debug=False):
self.debug = debug
def get_database_connection(self):
# 连接数据库的代码
def get_current_time():
return datetime.datetime.now()
- 設定を使用する必要がある場所でsettingsファイルをインポートする
from settings import DEBUG, LOG_FILE, AppConfig, get_current_time
以上の手順により、簡単な設定ファイルを作成できます。アプリケーションのニーズに応じて、必要に応じて追加の設定項目やオプションを追加できます。