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

style: make pre-commit happy #594

Merged
merged 3 commits into from
Oct 14, 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
32 changes: 32 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
exclude: "migrations"

repos:
- repo: https://github.com/asottile/pyupgrade
rev: v3.0.0
hooks:
- id: pyupgrade
args: ["--py37-plus"]

- repo: https://github.com/PyCQA/flake8
rev: 5.0.4
hooks:
- id: flake8

- repo: https://github.com/asottile/yesqa
rev: v1.4.0
hooks:
- id: yesqa

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.3.0
hooks:
- id: check-merge-conflict
- id: check-toml
- id: check-yaml
- id: mixed-line-ending

- repo: https://github.com/pycqa/isort
rev: 5.10.1
hooks:
- id: isort
1 change: 0 additions & 1 deletion django_celery_beat/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
# All rights reserved.
# :license: BSD (3 Clause), see LICENSE for more details.
import re

from collections import namedtuple

import django
Expand Down
20 changes: 8 additions & 12 deletions django_celery_beat/admin.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,17 @@
"""Periodic Task Admin interface."""
from celery import current_app
from celery.utils import cached_property
from django import forms
from django.conf import settings
from django.contrib import admin, messages
from django.db.models import When, Value, Case
from django.db.models import Case, Value, When
from django.forms.widgets import Select
from django.template.defaultfilters import pluralize
from django.utils.translation import gettext_lazy as _

from celery import current_app
from celery.utils import cached_property
from kombu.utils.json import loads

from .models import (
PeriodicTask, PeriodicTasks,
IntervalSchedule, CrontabSchedule,
SolarSchedule, ClockedSchedule
)
from .models import (ClockedSchedule, CrontabSchedule, IntervalSchedule,
PeriodicTask, PeriodicTasks, SolarSchedule)
from .utils import is_database_scheduler


Expand All @@ -26,7 +22,7 @@ class TaskSelectWidget(Select):
_choices = None

def tasks_as_choices(self):
_ = self._modules # noqa
_ = self._modules
tasks = list(sorted(name for name in self.celery_app.tasks
if not name.startswith('celery.')))
return (('', ''), ) + tuple(zip(tasks, tasks))
Expand Down Expand Up @@ -149,7 +145,7 @@ def changelist_view(self, request, extra_context=None):
extra_context = extra_context or {}
scheduler = getattr(settings, 'CELERYBEAT_SCHEDULER', None)
extra_context['wrong_scheduler'] = not is_database_scheduler(scheduler)
return super(PeriodicTaskAdmin, self).changelist_view(
return super().changelist_view(
request, extra_context)

def get_queryset(self, request):
Expand Down Expand Up @@ -215,7 +211,7 @@ def run_tasks(self, request, queryset):

self.message_user(
request,
_('task "{0}" not found'.format(not_found_task_name)),
_(f'task "{not_found_task_name}" not found'),
level=messages.ERROR,
)
return
Expand Down
3 changes: 2 additions & 1 deletion django_celery_beat/clockedschedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from celery import schedules
from celery.utils.time import maybe_make_aware

from .utils import NEVER_CHECK_TIMEOUT


Expand All @@ -27,7 +28,7 @@ def is_due(self, last_run_at):
return schedules.schedstate(is_due=False, next=remaining_s)

def __repr__(self):
return '<clocked: {}>'.format(self.clocked_time)
return f'<clocked: {self.clocked_time}>'

def __eq__(self, other):
if isinstance(other, clocked):
Expand Down
12 changes: 6 additions & 6 deletions django_celery_beat/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,21 +3,21 @@
from zoneinfo import available_timezones
except ImportError:
from backports.zoneinfo import available_timezones

from datetime import timedelta

import timezone_field
from celery import schedules, current_app
from celery import current_app, schedules
from django.conf import settings
from django.core.exceptions import MultipleObjectsReturned, ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models
from django.utils.translation import gettext_lazy as _

from . import querysets, validators
from .clockedschedule import clocked
from .tzcrontab import TzAwareCrontab
from .utils import make_aware, now
from .clockedschedule import clocked


DAYS = 'days'
HOURS = 'hours'
Expand Down Expand Up @@ -129,7 +129,7 @@ def from_schedule(cls, schedule):
return cls(**spec)

def __str__(self):
return '{0} ({1}, {2})'.format(
return '{} ({}, {})'.format(
self.get_event_display(),
self.latitude,
self.longitude
Expand Down Expand Up @@ -224,7 +224,7 @@ class Meta:
ordering = ['clocked_time']

def __str__(self):
return '{}'.format(make_aware(self.clocked_time))
return f'{make_aware(self.clocked_time)}'

@property
def schedule(self):
Expand Down Expand Up @@ -314,7 +314,7 @@ class Meta:
'day_of_week', 'hour', 'minute', 'timezone']

def __str__(self):
return '{0} {1} {2} {3} {4} (m/h/dM/MY/d) {5}'.format(
return '{} {} {} {} {} (m/h/dM/MY/d) {}'.format(
cronexp(self.minute), cronexp(self.hour),
cronexp(self.day_of_month), cronexp(self.month_of_year),
cronexp(self.day_of_week), str(self.timezone)
Expand Down
27 changes: 10 additions & 17 deletions django_celery_beat/schedulers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,22 @@
import datetime
import logging
import math

from multiprocessing.util import Finalize

from celery import current_app
from celery import schedules
from celery.beat import Scheduler, ScheduleEntry

from celery import current_app, schedules
from celery.beat import ScheduleEntry, Scheduler
from celery.utils.log import get_logger
from celery.utils.time import maybe_make_aware
from kombu.utils.encoding import safe_str, safe_repr
from kombu.utils.json import dumps, loads

from django.conf import settings
from django.db import transaction, close_old_connections
from django.db.utils import DatabaseError, InterfaceError
from django.core.exceptions import ObjectDoesNotExist
from django.db import close_old_connections, transaction
from django.db.utils import DatabaseError, InterfaceError
from kombu.utils.encoding import safe_repr, safe_str
from kombu.utils.json import dumps, loads

from .models import (
PeriodicTask, PeriodicTasks,
CrontabSchedule, IntervalSchedule,
SolarSchedule, ClockedSchedule
)
from .clockedschedule import clocked
from .models import (ClockedSchedule, CrontabSchedule, IntervalSchedule,
PeriodicTask, PeriodicTasks, SolarSchedule)
from .utils import NEVER_CHECK_TIMEOUT

# This scheduler must wake up more frequently than the
Expand Down Expand Up @@ -169,7 +162,7 @@ def to_model_schedule(cls, schedule):
model_schedule.save()
return model_schedule, model_field
raise ValueError(
'Cannot convert schedule type {0!r} to model'.format(schedule))
f'Cannot convert schedule type {schedule!r} to model')

@classmethod
def from_entry(cls, name, app=None, **entry):
Expand Down Expand Up @@ -205,7 +198,7 @@ def _unpack_options(cls, queue=None, exchange=None, routing_key=None,
}

def __repr__(self):
return '<ModelEntry: {0} {1}(*{2}, **{3}) {4}>'.format(
return '<ModelEntry: {} {}(*{}, **{}) {}>'.format(
safe_str(self.name), self.task, safe_repr(self.args),
safe_repr(self.kwargs), self.schedule,
)
Expand Down
18 changes: 7 additions & 11 deletions django_celery_beat/signals.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
"""Django Application signals."""


def signals_connect():
"""
Connect to signals.
"""
"""Connect to signals."""
from django.db.models import signals
from .models import (
ClockedSchedule,
PeriodicTask,
PeriodicTasks,
IntervalSchedule,
CrontabSchedule,
SolarSchedule
)

from .models import (ClockedSchedule, CrontabSchedule, IntervalSchedule,
PeriodicTask, PeriodicTasks, SolarSchedule)

signals.pre_save.connect(
PeriodicTasks.changed, sender=PeriodicTask
Expand Down
3 changes: 1 addition & 2 deletions django_celery_beat/tzcrontab.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
"""Timezone aware Cron schedule Implementation."""
from celery import schedules

from collections import namedtuple
from datetime import datetime, timezone

from celery import schedules

schedstate = namedtuple('schedstate', ('is_due', 'next'))

Expand Down
1 change: 1 addition & 0 deletions django_celery_beat/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def is_database_scheduler(scheduler):
if not scheduler:
return False
from kombu.utils import symbol_by_name

from .schedulers import DatabaseScheduler
return (
scheduler == 'django'
Expand Down
22 changes: 12 additions & 10 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import os

from sphinx_celery import conf
Expand All @@ -23,16 +22,19 @@
r'django_celery_beat.migrations.*',
],
extlinks={
'github_project': (
'https://github.com/%s',
'GitHub project %s',
),
'github_pr': (
'https://github.com/celery/django-celery-beat/pull/%s',
'GitHub PR #%s',
),
'github_project': (
'https://github.com/%s',
'GitHub project %s',
),
'github_pr': (
'https://github.com/celery/django-celery-beat/pull/%s',
'GitHub PR #%s',
),
},
extra_intersphinx_mapping={
'django-celery-results': ('https://django-celery-results.readthedocs.io/en/latest/', None),
'django-celery-results': (
'https://django-celery-results.readthedocs.io/en/latest/',
None
),
},
))
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ DJANGO_SETTINGS_MODULE=t.proj.settings
# classes can be lowercase, arguments and variables can be uppercase
# whenever it makes the code more readable.
ignore = N806, N802, N801, N803, W503, W504
exclude =
**/migrations/*.py

[pep257]
ignore = D102,D104,D203,D105,D213
Expand Down
14 changes: 9 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def _pyimp():
NAME = 'django-celery-beat'
PACKAGE = 'django_celery_beat'

E_UNSUPPORTED_PYTHON = '%s 1.0 requires %%s %%s or later!' % (NAME,)
E_UNSUPPORTED_PYTHON = f'{NAME} 1.0 requires %s %s or later!'

PYIMP = _pyimp()
PY37_OR_LESS = sys.version_info < (3, 7)
Expand Down Expand Up @@ -65,6 +65,7 @@ def add_default(m):
def add_doc(m):
return (('doc', m.groups()[0]),)


pats = {re_meta: add_default,
re_doc: add_doc}
here = os.path.abspath(os.path.dirname(__file__))
Expand All @@ -80,8 +81,9 @@ def add_doc(m):

# -*- Installation Requires -*-

def strip_comments(l):
return l.split('#', 1)[0].strip()

def strip_comments(line):
return line.split('#', 1)[0].strip()


def _pip_requirement(req):
Expand All @@ -94,7 +96,7 @@ def _pip_requirement(req):
def _reqs(*f):
return [
_pip_requirement(r) for r in (
strip_comments(l) for l in open(
strip_comments(line) for line in open(
os.path.join(os.getcwd(), 'requirements', *f)).readlines()
) if r]

Expand All @@ -104,11 +106,12 @@ def reqs(*f):

# -*- Long Description -*-


if os.path.exists('README.rst'):
long_description = codecs.open('README.rst', 'r', 'utf-8').read()
long_description_content_type = 'text/x-rst'
else:
long_description = 'See http://pypi.python.org/pypi/%s' % (NAME,)
long_description = f'See http://pypi.python.org/pypi/{NAME}'
long_description_content_type = 'text/markdown'

# -*- %%% -*-
Expand All @@ -125,6 +128,7 @@ def run_tests(self):
import pytest
sys.exit(pytest.main(self.pytest_args))


setuptools.setup(
name=NAME,
packages=setuptools.find_packages(exclude=[
Expand Down
7 changes: 3 additions & 4 deletions t/unit/conftest.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import pytest

# we have to import the pytest plugin fixtures here,
# in case user did not do the `python setup.py develop` yet,
# that installs the pytest plugin into the setuptools registry.
from celery.contrib.pytest import (celery_app, celery_enable_logging,
celery_parameters, depends_on_current_app,
celery_config, use_celery_app_trap)
from celery.contrib.pytest import (celery_app, celery_config,
celery_enable_logging, celery_parameters,
depends_on_current_app, use_celery_app_trap)
from celery.contrib.testing.app import TestApp, Trap

# Tricks flake8 into silencing redefining fixtures warnings.
Expand Down
Loading