django wait for database

Solutions on MaxInterview for django wait for database by the best coders in the world

showing results for - "django wait for database"
Sara
14 Aug 2019
1import time
2import sys
3
4from django.db import OperationalError, connections
5
6def write(message):
7    sys.stderr.write(message)
8    sys.stderr.flush()
9
10def database_ready(database: str = "default", maximum_wait: int = 15) -> bool:
11    write("waiting for database...")
12    connected, start = False, time.time()
13    while not connected and time.time() - start < maximum_wait:
14        try:
15            connections[database].cursor().execute("SELECT 1")
16            connected = True
17        except OperationalError:
18            write("waiting for database...")
19            time.sleep(maximum_wait // 3)
20    if time.time() - start > maximum_wait:
21        raise OperationalError("Could not connect to database.")
22    return connected
23
24# myproject/wsgi.py & asgi.py
25"""
26Wait for the default database to be ready before loading the application
27"""
28import os
29
30from django.core.wsgi import get_wsgi_application
31
32import utils
33
34os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")
35utils.database_ready("default", maximum_wait=15)
36
37application = get_wsgi_application()
38
39# myproject/management/commands/migrate.py
40"""
41Wait for the default database to bre ready before running migrations
42"""
43from django.core.management.commands.migrate import Command
44
45from corrdyn_creds import utils
46
47class Command(Command):
48    def handle(self, *args, **options):
49        utils.database_ready("default", maximum_wait=15)
50        super().handle(*args, **options)