Django: running code every time it starts, but after database migration

I thought that in recent versions of Django there was a simple answer, but I can not find it.

I have code that relates to a database. I want it to start every time Django starts. I seem to have two options:

Option 1. AppConfig.ready() - this works, but also runs until the database tables are created (i.e., during tests or when the application is reinitialized without data). If I use this, I should catch a few types of Exceptions and assume that the reason is empty db:

def is_db_init_error(e, table_name):
    return ("{}' doesn't exist".format(table_name) in str(e) or
            "no such table: {}".format(table_name) in str(e)
    )

try:
    # doing stuff 
except Exception as e:
    if not is_db_init_error(e, 'foo'):
        raise
    else:
        logger.warn("Skipping updating Foo object as db table doesn't exist")

Option 2. Use post_migrate.connect(foo_init, sender=self)- but this only happens during migration.

3. - urls.py - urls.py, , AppConfig

2 - / 1, 3 , urls.py .

2 , - , , , . , db , , .

+10
1

connection_created, :

, . , - SQL.

, , .

, :


, . , .


:
post_migrate connection_created AppConfig.ready() (, post_migrate post_migrate):

from django.apps import AppConfig
from django.db.models.signals import post_migrate, connection_created
# OR for Django 2.0+
# django.db.backends.signals import post_migrate, connection_created

migration_happened = false

def post_migration_callback(sender, **kwargs):
    ...
    migration_happened = true


def init_my_app(sender, connection):
    ...


class MyAppConfig(AppConfig):
    ...

    def ready(self):
        post_migrate.connect(post_migration_callback, sender=self)

        if !migration_happened:
            connection_created.connect(init_my_app, sender=self)
+3

Source: https://habr.com/ru/post/1674752/


All Articles