Skip to content

Commit d9fcfd1

Browse files
committed
Merge branch 'dont-use-imp-module'
2 parents 4be9fb0 + a80900f commit d9fcfd1

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

django_lightweight_queue/cron_scheduler.py

Lines changed: 14 additions & 18 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
6-
from typing import Any, cast, Dict, List, Tuple, Callable, Optional, Sequence
6+
from typing import Any, 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,24 +133,19 @@ 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

152-
for row in cast(List[CronConfig], mod.CONFIG):
147+
app_cron_config: List[CronConfig] = mod.CONFIG # type: ignore[attr-defined]
148+
for row in app_cron_config:
153149
row['min_matcher'] = get_matcher(0, 59, row.get('minutes'))
154150
row['hour_matcher'] = get_matcher(0, 23, row.get('hours'))
155151
row['day_matcher'] = get_matcher(1, 7, row.get('days', '*'))

0 commit comments

Comments
 (0)