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:
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 , , .