Skip to content

Commit f534c52

Browse files
committed
ruff
1 parent bfd47c3 commit f534c52

File tree

12 files changed

+43
-43
lines changed

12 files changed

+43
-43
lines changed

scheduler/admin/task_admin.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,14 @@
1515
from scheduler.settings import SCHEDULER_CONFIG, logger
1616

1717

18+
def job_execution_of(job: JobModel, task: Task) -> bool:
19+
return job.scheduled_task_id == task.id and job.task_type == task.task_type
20+
21+
1822
def get_job_executions_for_task(queue_name: str, scheduled_task: Task) -> List[JobModel]:
1923
queue = get_queue(queue_name)
2024
job_list: List[JobModel] = JobModel.get_many(queue.queued_job_registry.all(), connection=queue.connection)
21-
res = sorted(list(filter(lambda j: j.is_execution_of(scheduled_task), job_list)),
25+
res = sorted(list(filter(lambda j: job_execution_of(j, scheduled_task), job_list)),
2226
key=lambda j: j.created_at,
2327
reverse=True)
2428
return res

scheduler/decorators.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
from functools import wraps
22
from typing import Any, Callable, Dict, List, Optional, Union
33

4-
from scheduler.broker_types import ConnectionType, FunctionReferenceType
4+
from scheduler.broker_types import ConnectionType
5+
from scheduler.helpers.callback import Callback
56

67
JOB_METHODS_LIST = list()
78

89

910
class job:
1011
def __init__(
1112
self,
12-
queue: Union["Queue", str, None] = None,
13+
queue: Union["Queue", str, None] = None, # noqa: F821
1314
connection: Optional[ConnectionType] = None,
1415
timeout: Optional[int] = None,
1516
result_ttl: Optional[int] = None,

scheduler/helpers/callback.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
import inspect
33
from typing import Union, Callable, Any, Optional
44

5-
from scheduler.settings import SCHEDULER_CONFIG
65
from scheduler.timeouts import JobTimeoutException
76

87

@@ -12,6 +11,8 @@ class CallbackSetupError(Exception):
1211

1312
class Callback:
1413
def __init__(self, func: Union[str, Callable[..., Any]], timeout: Optional[int] = None):
14+
from scheduler.settings import SCHEDULER_CONFIG
15+
1516
self.timeout = timeout or SCHEDULER_CONFIG.CALLBACK_TIMEOUT
1617
if not isinstance(self.timeout, int) or self.timeout < 0:
1718
raise CallbackSetupError(f"Callback `timeout` must be a positive int, but received {self.timeout}")
@@ -26,6 +27,8 @@ def name(self) -> str:
2627
return "{0}.{1}".format(self.func.__module__, self.func.__qualname__)
2728

2829
def __call__(self, *args, **kwargs):
30+
from scheduler.settings import SCHEDULER_CONFIG
31+
2932
with SCHEDULER_CONFIG.DEATH_PENALTY_CLASS(self.timeout, JobTimeoutException):
3033
return self.func(*args, **kwargs)
3134

scheduler/helpers/queues/queue_logic.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ def create_and_enqueue_job(
259259
scheduled_task_id=scheduled_task_id,
260260
)
261261
if when is None:
262-
job_model = self._enqueue_job(job_model, connection=pipeline, at_front=at_front)
262+
job_model = self.enqueue_job(job_model, connection=pipeline, at_front=at_front)
263263
else:
264264
job_model.save(connection=self.connection)
265265
self.scheduled_job_registry.schedule(self.connection, job_model, when)
@@ -287,7 +287,7 @@ def job_handle_failure(self, status: JobStatus, job: JobModel, exc_string: str,
287287
exc_string=exc_string
288288
)
289289

290-
def run_job(self, job: JobModel) -> Any:
290+
def run_job(self, job: JobModel) -> JobModel:
291291
"""Run the job
292292
:param job: The job to run
293293
:returns: The job result
@@ -300,22 +300,22 @@ def run_job(self, job: JobModel) -> Any:
300300
self.job_handle_success(job, result=result, result_ttl=result_ttl, connection=pipeline)
301301
job.expire(result_ttl, connection=pipeline)
302302
pipeline.execute()
303-
return result
304-
except:
303+
except Exception as e:
304+
logger.warning(f"Job {job.name} failed with exception: {e}")
305305
with self.connection.pipeline() as pipeline:
306306
exc_string = "".join(traceback.format_exception(*sys.exc_info()))
307307
self.job_handle_failure(JobStatus.FAILED, job, exc_string, pipeline)
308308
pipeline.execute()
309+
return job
309310

310311
def retry_job(self, job: JobModel, connection: ConnectionType):
311312
"""Requeue or schedule this job for execution.
312313
If the the `retry_interval` was set on the job itself,
313314
it will calculate a scheduled time for the job to run, and instead
314315
of just regularly `enqueing` the job, it will `schedule` it.
315316
316-
Args:
317-
job (JobModel): The queue to retry the job on
318-
connection (ConnectionType): The Redis' pipeline to use
317+
:param job: The job to retry
318+
:param connection: The broker connection to use
319319
"""
320320
number_of_intervals = len(job.retry_intervals)
321321
index = max(number_of_intervals - job.retries_left, 0)
@@ -327,9 +327,9 @@ def retry_job(self, job: JobModel, connection: ConnectionType):
327327
job.save(connection=connection)
328328
self.scheduled_job_registry.schedule(connection, job, scheduled_datetime)
329329
else:
330-
self._enqueue_job(job, connection=connection)
330+
self.enqueue_job(job, connection=connection)
331331

332-
def _enqueue_job(
332+
def enqueue_job(
333333
self, job_model: JobModel, connection: Optional[ConnectionType] = None, at_front: bool = False
334334
) -> JobModel:
335335
"""Enqueues a job for delayed execution without checking dependencies.
@@ -369,7 +369,7 @@ def run_sync(self, job: JobModel) -> JobModel:
369369
job.prepare_for_execution("sync", self.active_job_registry, self.connection)
370370

371371
try:
372-
result = self.run_job(job)
372+
self.run_job(job)
373373
except: # noqa
374374
with self.connection.pipeline() as pipeline:
375375
exc_string = "".join(traceback.format_exception(*sys.exc_info()))
@@ -503,7 +503,7 @@ def requeue_jobs(self, *job_names: str, at_front: bool = False) -> int:
503503
job.started_at = None
504504
job.ended_at = None
505505
job.save(connection=pipe)
506-
self._enqueue_job(job, connection=pipe, at_front=at_front)
506+
self.enqueue_job(job, connection=pipe, at_front=at_front)
507507
jobs_requeued += 1
508508
pipe.execute()
509509
return jobs_requeued

scheduler/management/commands/scheduler_worker.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ def handle(self, **options):
134134
# Verbosity is defined by default in BaseCommand for all commands
135135
verbosity = options.pop("verbosity", 3)
136136
log_level = VERBOSITY_TO_LOG_LEVEL.get(verbosity, logging.INFO)
137+
logger.setLevel(log_level)
137138
logger.setLevel(logging.DEBUG)
138139
logging.basicConfig(level=logging.DEBUG)
139140

scheduler/models/task.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import math
2-
import uuid
32
from datetime import timedelta, datetime
43
from typing import Dict, Any, Optional
54

@@ -190,9 +189,9 @@ def is_scheduled(self) -> bool:
190189
return False
191190
# check whether job_id is in scheduled/queued/active jobs
192191
res = (
193-
(self.job_id in self.rqueue.scheduled_job_registry.all())
194-
or (self.job_id in self.rqueue.queued_job_registry.all())
195-
or (self.job_id in self.rqueue.active_job_registry.all())
192+
(self.job_id in self.rqueue.scheduled_job_registry.all())
193+
or (self.job_id in self.rqueue.queued_job_registry.all())
194+
or (self.job_id in self.rqueue.active_job_registry.all())
196195
)
197196
# If the job_id is not scheduled/queued/started,
198197
# update the job_id to None. (The job_id belongs to a previous run which is completed)

scheduler/redis_models/job.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,6 @@ def set_status(self, status: JobStatus, connection: ConnectionType) -> None:
8585
"""Set's the Job Status"""
8686
self.set_field("status", status, connection=connection)
8787

88-
def is_execution_of(self, task: "Task") -> bool:
89-
return self.scheduled_task_id == task.id and self.task_type == task.task_type
90-
9188
@property
9289
def is_queued(self) -> bool:
9390
return self.status == JobStatus.QUEUED
@@ -168,7 +165,7 @@ def stopped_callback(self) -> Optional[Callable[..., Any]]:
168165
return Callback(self.stopped_callback_name, self.stopped_callback_timeout)
169166

170167
def get_call_string(self):
171-
return get_call_string(self.func_name, self.args, self.kwargs)
168+
return _get_call_string(self.func_name, self.args, self.kwargs)
172169

173170
@classmethod
174171
def create(
@@ -233,7 +230,7 @@ def create(
233230
_func_name = "__call__"
234231
else:
235232
raise TypeError("Expected a callable or a string, but got: {0}".format(func))
236-
description = description or get_call_string(func, args or [], kwargs or {}, max_length=75)
233+
description = description or _get_call_string(func, args or [], kwargs or {}, max_length=75)
237234

238235
if retries_left is not None and retries_left < 1:
239236
raise ValueError("max: please enter a value greater than 0")
@@ -283,22 +280,19 @@ def create(
283280
return model
284281

285282

286-
def get_call_string(
283+
def _get_call_string(
287284
func_name: Optional[str], args: Any, kwargs: Dict[Any, Any], max_length: Optional[int] = None
288285
) -> Optional[str]:
289286
"""
290287
Returns a string representation of the call, formatted as a regular
291288
Python function invocation statement. If max_length is not None, truncate
292289
arguments with representation longer than max_length.
293290
294-
Args:
295-
func_name (str): The funtion name
296-
args (Any): The function arguments
297-
kwargs (Dict[Any, Any]): The function kwargs
298-
max_length (int, optional): The max length. Defaults to None.
299-
300-
Returns:
301-
str: A String representation of the function call.
291+
:param func_name: The function name
292+
:param args: The function arguments
293+
:param kwargs: The function kwargs
294+
:param max_length: The max length of the return string
295+
:return: A string representation of the function call
302296
"""
303297
if func_name is None:
304298
return None

scheduler/tests/test_views/test_queue_job_action.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,11 +74,9 @@ def test_single_job_action_enqueue_job(self):
7474
queue = get_queue("django_tasks_scheduler_test")
7575
job_list = []
7676
# enqueue some jobs that depends on other
77-
previous_job = None
7877
for _ in range(0, 3):
7978
job = queue.create_and_enqueue_job(test_job)
8079
job_list.append(job)
81-
previous_job = job
8280

8381
# This job is deferred
8482

scheduler/tests/testtools.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from django.utils import timezone
1010

1111
from scheduler import settings
12+
from scheduler.admin.task_admin import job_execution_of
1213
from scheduler.helpers.queues import get_queue
1314
from scheduler.helpers.tools import create_worker
1415
from scheduler.models.args import TaskKwarg
@@ -113,10 +114,10 @@ def _get_task_scheduled_job_from_registry(django_task: Task) -> JobModel:
113114
return JobModel.get(entry, connection=django_task.rqueue.connection)
114115

115116

116-
def _get_executions(django_job: Task):
117-
job_ids = django_job.rqueue.get_all_job_names()
118-
job_list: List[JobModel] = JobModel.get_many(job_ids, connection=django_job.rqueue.connection)
119-
return list(filter(lambda j: j.is_execution_of(django_job), job_list))
117+
def _get_executions(task: Task):
118+
job_ids = task.rqueue.get_all_job_names()
119+
job_list: List[JobModel] = JobModel.get_many(job_ids, connection=task.rqueue.connection)
120+
return list(filter(lambda j: job_execution_of(j, task), job_list))
120121

121122

122123
class SchedulerBaseCase(TestCase):

scheduler/views/job_views.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def job_action(request: HttpRequest, job_name: str, action: str) -> HttpResponse
7878
return redirect("queue_registry_jobs", queue.name, "queued")
7979
elif action == "enqueue":
8080
queue.delete_job(job.name)
81-
queue._enqueue_job(job)
81+
queue.enqueue_job(job)
8282
messages.info(request, f"You have successfully enqueued {job.name}")
8383
return redirect("job_details", job_name)
8484
elif action == "cancel":

0 commit comments

Comments
 (0)