📜  django 等待数据库 - Python 代码示例

📅  最后修改于: 2022-03-11 14:45:47.091000             🧑  作者: Mango

代码示例1
import time
import sys

from django.db import OperationalError, connections

def write(message):
    sys.stderr.write(message)
    sys.stderr.flush()

def database_ready(database: str = "default", maximum_wait: int = 15) -> bool:
    write("waiting for database...")
    connected, start = False, time.time()
    while not connected and time.time() - start < maximum_wait:
        try:
            connections[database].cursor().execute("SELECT 1")
            connected = True
        except OperationalError:
            write("waiting for database...")
            time.sleep(maximum_wait // 3)
    if time.time() - start > maximum_wait:
        raise OperationalError("Could not connect to database.")
    return connected

# myproject/wsgi.py & asgi.py
"""
Wait for the default database to be ready before loading the application
"""
import os

from django.core.wsgi import get_wsgi_application

import utils

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
utils.database_ready("default", maximum_wait=15)

application = get_wsgi_application()

# myproject/management/commands/migrate.py
"""
Wait for the default database to bre ready before running migrations
"""
from django.core.management.commands.migrate import Command

from corrdyn_creds import utils

class Command(Command):
    def handle(self, *args, **options):
        utils.database_ready("default", maximum_wait=15)
        super().handle(*args, **options)