[django | command] Build a Backend REST API - 19



Add wait_for_db_command💗


以前に設定したソースコードはテストソースコードであり、実際のカスタムコマンドを実行するソースコードの作成を開始します.

making a structure🎭

coreアプリケーションの下
commandsフォルダとinitを含む管理フォルダを作成します.それぞれPyを作ろう
次にcommandsフォルダにinitします.pyを再作成し、wait_for_db.pyファイルを生成

wait_for_db.pyの作成🎗

import time

from django.db import connections
from django.db.utils import OperationalError
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    """Django command to pause execution until database is available"""

    def handle(self, *args, **options):
        self.stdout.write('Waiting for database...')
        db_conn = None
        while not db_conn:
            try:
                db_conn = connections['default']
            except OperationalError:
                self.stdout.write('Database unavailable, waiting 1 second...')
                time.sleep(1)

        self.stdout.write(self.style.SUCCESS('Database available!'))

STEP1 import🧧


初回導入time2番目の次のDjangodbパッケージのconnectionsモジュールをインポートします.
  • データベースに接続できるかどうかを確認します.
  • 第三に、dbとの接続が使用できない場合は、エラーの原因となるクラスをインポートします.from django.db.utils import OperationalError4つ目はcustom commandバージョンのために「BaseCommand」をインポート
    import time
    
    from django.db import connections
    from django.db.utils import OperationalError
    from django.core.management.base import BaseCommand

    STEP2 class Command🎡

    BaseCommandを継承し、Commandクラスを作成します.
    参考までにDocstringを書くのは常に良い習慣なので、短いドキュメントを書いてください.
    また、Commnadクラスとhandleメソッドの名前は変更できません.これは私が倉庫で決めた名前だからです.handle()メソッドは、下図のように本文書に記載されている.
    実際の論理を実現する方法と考えられる.
    BaseCommand.handle(*args, **options)
    The actual logic of the command. Subclasses must implement this method.
    It may return a Unicode string which will be printed to stdout (wrapped by BEGIN; and COMMIT; if output_transaction is True).self.stdout.write('Waiting for database...')コードは画面に情報を表示します.
    db connn変数を作成します.値はNoneです.while not db_conn:はdb connがNone値やステータス変更ではなく別の値に割り当てられたときに終了します.そうしないと、データベースが接続されていない場合は、ループ文の実行を続行します.
    try ... except ...OperationalErrorを見つけ出す文章を書きます
    connection変数はConnectionHandlerというクラスを変数化したものです
    except OperationalError:
    self.stdout.write('Database unavailable, waiting 1 second...')
    time.sleep(1)
    このセクションでは、エラーが発生した場合、通知画面がデバイス接続を確立できないことを通知し、初期ブリッジであることを通知します.そして1秒止まります
    class Command(BaseCommand):
        """Django command to pause execution until database is available"""
    
        def handle(self, *args, **options):
            self.stdout.write('Waiting for database...')
            db_conn = None
            while not db_conn:
                try:
                    db_conn = connections['default']
                except OperationalError:
                    self.stdout.write('Database unavailable, waiting 1 second...')
                    time.sleep(1)
    
            self.stdout.write(self.style.SUCCESS('Database available!'))