Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #123 -- init broker configuration before loading other app models #126

Merged
merged 3 commits into from
Nov 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions django_dramatiq/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,22 @@ class DjangoDramatiqConfig(AppConfig):
name = "django_dramatiq"
verbose_name = "Django Dramatiq"

def import_models(self):
"""
Initialize Dramatiq configuration right after Django has loaded its models.

Django calls `ready()` on all apps only after it has loaded all models.
Due to the fact that tasks often imported from models, we need to make sure
that Dramatiq is fully configured before that happens.
"""
super().import_models()
self.ready()

def ready(self):
if getattr(self, "_is_ready", False):
return
super().ready()

global RATE_LIMITER_BACKEND
dramatiq.set_encoder(self.select_encoder())

Expand Down Expand Up @@ -76,6 +91,8 @@ def ready(self):
broker = broker_class(middleware=middleware, **broker_options)
dramatiq.set_broker(broker)

self._is_ready = True

@property
def rate_limiter_backend(self):
return type(self).get_rate_limiter_backend()
Expand Down
3 changes: 3 additions & 0 deletions tests/testapp1/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@

class Testapp1Config(AppConfig):
name = "tests.testapp1"

def ready(self):
from . import tasks # noqa
2 changes: 2 additions & 0 deletions tests/testapp1/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Quite common use-case when you want to run tasks within models.py code
from tests.testapp1 import tasks # noqa