Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

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)
Comment

PREVIOUS NEXT
Code Example
Python :: openpyxl change sheet name 
Python :: ses mail name 
Python :: Install Basemap on Python 
Python :: index of sorted list python 
Python :: normalize rows in matrix numpy 
Python :: import random py 
Python :: get current directory python 
Python :: python filter a dictionary 
Python :: sys get current pythonpath 
Python :: pandas object to float 
Python :: find nan value in dataframe python 
Python :: all possible combinations of parameters 
Python :: how to roll longitude axis 
Python :: python: select specific columns in a data frame 
Python :: delete a row in pandas dataframe 
Python :: python speech recognition module 
Python :: python get lines from text file 
Python :: pandas join two series on index 
Python :: python selenium type in input 
Python :: print() in python 
Python :: python des 
Python :: pandas repeat rows n times 
Python :: selenium python 
Python :: python index of last occurrence in string 
Python :: libreoffice add line in table 
Python :: round list of floats python 
Python :: parse list from string 
Python :: compute mad python 
Python :: discord get user slash command 
Python :: python join paths 
ADD CONTENT
Topic
Content
Source link
Name
7+7 =