Horje
django wait for database Code Example
django wait for database
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)




Python

Related
libreoffice add line in table Code Example libreoffice add line in table Code Example
an array of dates python Code Example an array of dates python Code Example
libreoffice add row at the end of table Code Example libreoffice add row at the end of table Code Example
ImportError: cannot import name 'TFAutoModel' from 'transformers' Code Example ImportError: cannot import name 'TFAutoModel' from 'transformers' Code Example
pandas dataframe convert yes no to 0 1 Code Example pandas dataframe convert yes no to 0 1 Code Example

Type:
Code Example
Category:
Coding
Sub Category:
Code Example
Uploaded by:
Admin
Views:
7