Skip to content

Commit 450a219

Browse files
committed
Modernise cron configuration import mechanics
As far as I can tell this is functionally equivalent to the previous approach, however uses a mixture of supported Python and Django import utils rather than relying on `__import__` (which is discouraged) and the deprecated `imp` module. This resolves deprecation warnings as well as some resource warnings that originated from the previous `imp.find_module` call.
1 parent 7dd1dff commit 450a219

File tree

1 file changed

+11
-16
lines changed

1 file changed

+11
-16
lines changed

django_lightweight_queue/cron_scheduler.py

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
import re
2-
import imp
32
import time
43
import datetime
4+
import importlib
55
import threading
66
from typing import Any, cast, Dict, List, Tuple, Callable, Optional, Sequence
77

88
from typing_extensions import TypedDict
99

1010
from django.apps import apps
1111
from django.core.management import call_command
12+
from django.utils.module_loading import module_has_submodule
1213

1314
from .task import task
1415
from .types import QueueName
@@ -132,22 +133,16 @@ def get_matcher(minval, maxval, t):
132133
return lambda x: x in t_parts
133134

134135
for app_config in apps.get_app_configs():
135-
app = app_config.name
136+
# Adapted from django.utils.module_loading.autodiscover_modules
136137
try:
137-
# __import__ will break with anything other than a str object(!),
138-
# including e.g. unicode. So force to a str.
139-
part = str(app.split('.')[-1])
140-
141-
app_path = __import__(app, {}, {}, [part]).__path__
142-
except AttributeError:
143-
continue
144-
145-
try:
146-
imp.find_module('cron', app_path)
147-
except ImportError:
148-
continue
149-
150-
mod = __import__('{}.cron'.format(app), fromlist=(app,))
138+
mod = importlib.import_module(f'{app_config.name}.cron')
139+
except Exception:
140+
if module_has_submodule(app_config.module, 'cron'):
141+
# The module exists, so the error was something it did -- bubble the error.
142+
raise
143+
else:
144+
# No module, move on.
145+
continue
151146

152147
for row in cast(List[CronConfig], mod.CONFIG):
153148
row['min_matcher'] = get_matcher(0, 59, row.get('minutes'))

0 commit comments

Comments
 (0)