Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to disable Database status check at startup?

As far as I know Django apps can't start if any of the databases set in the settings.py are down at the start of the application. Is there anyway to make Django "lazyload" the initial database connection?

I have two databases configured and one of them is a little unstable and sometimes it can be down for some seconds, but it's only used for some specific use cases of the application. As you can imagine I don't want that all the application can't start because of that. Is there any solution for that?

I'm using Django 1.6.11, and we also use Django South for database migrations (in case that it's related somehow).

like image 330
Israel Fonseca Avatar asked Jul 21 '17 14:07

Israel Fonseca


People also ask

Can you use Django without a database?

Although you can use Django without a database, it comes with an object-relational mapper in which you describe your database layout in Python code.

What is AppConfig Django?

The AppConfig class used to configure the application has a path class attribute, which is the absolute directory path Django will use as the single base path for the application.

What database does Django use by default?

By default, the configuration uses SQLite. If you're new to databases, or you're just interested in trying Django, this is the easiest choice. SQLite is included in Python, so you won't need to install anything else to support your database.


2 Answers

I do not know how safe it is but you can do the following:

  1. In your settings.py start with empty DATABASES:

    DATABASES = {}
    
  2. In your apps.py, utilize the ready() hook to establish your database connections:

    from settings.py import DATABASES
    
    class YourAppConfig(AppConfig):
    
        def ready(self):
            DATABASES.update({
                Your database connections
            })
    

Now I cannot place my hand over fire for that one, but Django will try to reinitialize the database connection when needed.

like image 136
John Moutafis Avatar answered Oct 15 '22 00:10

John Moutafis


I did some more tests and problem only happens when you are using de development server python manage.py runserver. In that case, it forces a connection with the database.

Using an actual WSGI server it doesn't happen as @Alasdair informed.

@JohnMoutafis in the end I didn't test your solution, but that could work.

like image 41
Israel Fonseca Avatar answered Oct 15 '22 02:10

Israel Fonseca