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

Replace flake8, isort, and pyupgrade with ruff #707

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from 2 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
26 changes: 7 additions & 19 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,6 @@
exclude: "migrations"

repos:
- repo: https://github.com/asottile/pyupgrade
rev: v3.15.0
hooks:
- id: pyupgrade
args: ["--py37-plus"]
Comment on lines -5 to -9
Copy link
Contributor Author

@cclauss cclauss Dec 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.


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

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

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
Expand All @@ -26,7 +10,11 @@ repos:
- id: check-yaml
- id: mixed-line-ending

- repo: https://github.com/pycqa/isort
rev: 5.13.2
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.8
hooks:
- id: isort
# Run the linter.
- id: ruff
# args: [ --fix ]
# Run the formatter.
# - id: ruff-format
30 changes: 5 additions & 25 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@ PYTEST=pytest
GIT=git
TOX=tox
ICONV=iconv
FLAKE8=flake8
FLAKEPLUS=flakeplus
PYDOCSTYLE=pydocstyle
RUFF=ruff
SPHINX2RST=sphinx2rst

SPHINX_DIR=docs/
Expand All @@ -18,7 +16,6 @@ CONTRIBUTING=CONTRIBUTING.rst
CONTRIBUTING_SRC="docs/contributing.rst"
SPHINX_HTMLDIR="${SPHINX_BUILDDIR}/html"
DOCUMENTATION=Documentation
FLAKEPLUSTARGET=2.7

TESTDIR=t

Expand All @@ -34,10 +31,7 @@ help:
@echo " configcheck - Check configuration reference coverage."
@echo " readmecheck - Check README.rst encoding."
@echo " contribcheck - Check CONTRIBUTING.rst encoding"
@echo " flakes -------- - Check code for syntax and style errors."
@echo " flakecheck - Run flake8 on the source code."
@echo " flakepluscheck - Run flakeplus on the source code."
@echo " pep257check - Run flakeplus on the source code."
@echo " ruff ---------- - Check code for syntax and style errors."
@echo "readme - Regenerate README.rst file."
@echo "contrib - Regenerate CONTRIBUTING.rst file"
@echo "clean-dist --------- - Clean all distribution build artifacts."
Expand Down Expand Up @@ -76,30 +70,16 @@ docs: Documentation
clean-docs:
-rm -rf "$(SPHINX_BUILDDIR)"

lint: flakecheck apicheck configcheck readmecheck
lint: ruff apicheck configcheck readmecheck

apicheck:
(cd "$(SPHINX_DIR)"; $(MAKE) apicheck)

configcheck:
true

flakecheck:
$(FLAKE8) "$(PROJ)" "$(TESTDIR)"

flakediag:
-$(MAKE) flakecheck

flakepluscheck:
$(FLAKEPLUS) --$(FLAKEPLUSTARGET) "$(PROJ)" "$(TESTDIR)"

flakeplusdiag:
-$(MAKE) flakepluscheck

pep257check:
$(PYDOCSTYLE) "$(PROJ)"

flakes: flakediag flakeplusdiag pep257check
ruff:
$(RUFF) .

clean-readme:
-rm -f $(README)
Expand Down
7 changes: 3 additions & 4 deletions django_celery_beat/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@
from django.utils.translation import gettext_lazy as _
from kombu.utils.json import loads

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


Expand All @@ -23,8 +22,8 @@ class TaskSelectWidget(Select):

def tasks_as_choices(self):
_ = self._modules
tasks = list(sorted(name for name in self.celery_app.tasks
if not name.startswith('celery.')))
tasks = sorted(name for name in self.celery_app.tasks
if not name.startswith('celery.'))
return (('', ''), ) + tuple(zip(tasks, tasks))

@property
Expand Down
2 changes: 1 addition & 1 deletion django_celery_beat/migrations/0003_auto_20161209_0049.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,6 @@ class Migration(migrations.Migration):
),
migrations.AlterUniqueTogether(
name='solarschedule',
unique_together=set([('event', 'latitude', 'longitude')]),
unique_together={('event', 'latitude', 'longitude')},
),
]
4 changes: 2 additions & 2 deletions django_celery_beat/migrations/0010_auto_20190429_0326.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Generated by Django 1.11.20 on 2019-04-29 03:26

# this file is auto-generated so don't do flake8 on it
# flake8: noqa
# this file is auto-generated so don't do ruff lint on it
# ruff: noqa
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
Expand Down
2 changes: 1 addition & 1 deletion django_celery_beat/migrations/0011_auto_20190508_0153.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Generated by Django 2.2 on 2019-05-08 01:53
# flake8: noqa
# ruff: noqa
from django.db import migrations, models
import django.db.models.deletion

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Generated by Django 2.2.4 on 2019-08-30 00:46
# flake8: noqa
# ruff: noqa
from django.db import migrations, models


Expand Down
2 changes: 1 addition & 1 deletion django_celery_beat/migrations/0013_auto_20200609_0727.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Generated by Django 3.0.6 on 2020-06-09 07:27
# flake8: noqa
# ruff: noqa
from django.db import migrations
import django_celery_beat.models
import timezone_field.fields
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Generated by Django 2.2.4 on 2019-08-30 00:46
# flake8: noqa
# ruff: noqa
from django.db import migrations


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Generated by Django 3.0.6 on 2020-12-13 15:00
# flake8: noqa
# ruff: noqa
from django.db import migrations, models


Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Generated by Django 4.0.3 on 2022-03-21 20:20
# flake8: noqa
# ruff: noqa
from django.db import migrations
import django_celery_beat.models
import timezone_field.fields
Expand Down
24 changes: 5 additions & 19 deletions django_celery_beat/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@

import timezone_field
from celery import current_app, schedules
from cron_descriptor import (FormatException, MissingFieldException,
WrongArgumentException, get_description)
from cron_descriptor import FormatException, MissingFieldException, WrongArgumentException, get_description
from django.conf import settings
from django.core.exceptions import MultipleObjectsReturned, ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator
Expand Down Expand Up @@ -131,11 +130,7 @@ def from_schedule(cls, schedule):
return cls(**spec)

def __str__(self):
return '{} ({}, {})'.format(
self.get_event_display(),
self.latitude,
self.longitude
)
return f'{self.get_event_display()} ({self.latitude}, {self.longitude})'


class IntervalSchedule(models.Model):
Expand Down Expand Up @@ -317,11 +312,7 @@ class Meta:

@property
def human_readable(self):
cron_expression = '{} {} {} {} {}'.format(
cronexp(self.minute), cronexp(self.hour),
cronexp(self.day_of_month), cronexp(self.month_of_year),
cronexp(self.day_of_week)
)
cron_expression = f'{cronexp(self.minute)} {cronexp(self.hour)} {cronexp(self.day_of_month)} {cronexp(self.month_of_year)} {cronexp(self.day_of_week)}'
try:
human_readable = get_description(cron_expression)
except (
Expand All @@ -333,11 +324,7 @@ def human_readable(self):
return f'{human_readable} {str(self.timezone)}'

def __str__(self):
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)
)
return f'{cronexp(self.minute)} {cronexp(self.hour)} {cronexp(self.day_of_month)} {cronexp(self.month_of_year)} {cronexp(self.day_of_week)} (m/h/dM/MY/d) {str(self.timezone)}'

@property
def schedule(self):
Expand Down Expand Up @@ -579,8 +566,7 @@ def validate_unique(self, *args, **kwargs):
'must be set.'
)

err_msg = 'Only one of clocked, interval, crontab, '\
'or solar must be set'
err_msg = 'Only one of clocked, interval, crontab, or solar must be set'
if len(selected_schedule_types) > 1:
error_info = {}
for selected_schedule_type in selected_schedule_types:
Expand Down
25 changes: 9 additions & 16 deletions django_celery_beat/schedulers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Beat Scheduler Implementation."""
import contextlib
import datetime
import logging
import math
Expand All @@ -16,8 +17,7 @@
from kombu.utils.json import dumps, loads

from .clockedschedule import clocked
from .models import (ClockedSchedule, CrontabSchedule, IntervalSchedule,
PeriodicTask, PeriodicTasks, SolarSchedule)
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 @@ -136,20 +136,20 @@ def is_due(self):
return self.schedule.is_due(last_run_at_in_tz)

def _default_now(self):
if getattr(settings, 'DJANGO_CELERY_BEAT_TZ_AWARE', True):
if getattr(settings, 'DJANGO_CELERY_BEAT_TZ_AWARE', True): # noqa: SIM108
now = datetime.datetime.now(self.app.timezone)
else:
# this ends up getting passed to maybe_make_aware, which expects
# all naive datetime objects to be in utc time.
now = datetime.datetime.utcnow()
now = datetime.datetime.utcnow() # utcnow() is deprecated in Python 3.12
return now

def __next__(self):
self.model.last_run_at = self._default_now()
self.model.total_run_count += 1
self.model.no_changes = True
return self.__class__(self.model)
next = __next__ # for 2to3
next = __next__ # for 2to3 # noqa: A003

def save(self):
# Object may not be synchronized, so only
Expand Down Expand Up @@ -209,10 +209,7 @@ def _unpack_options(cls, queue=None, exchange=None, routing_key=None,
}

def __repr__(self):
return '<ModelEntry: {} {}(*{}, **{}) {}>'.format(
safe_str(self.name), self.task, safe_repr(self.args),
safe_repr(self.kwargs), self.schedule,
)
return f'<ModelEntry: {safe_str(self.name)} {self.task}(*{safe_repr(self.args)}, **{safe_repr(self.kwargs)}) {self.schedule}>'


class DatabaseScheduler(Scheduler):
Expand Down Expand Up @@ -245,10 +242,8 @@ def all_as_schedule(self):
debug('DatabaseScheduler: Fetching database schedule')
s = {}
for model in self.Model.objects.enabled():
try:
with contextlib.suppress(ValueError):
s[model.name] = self.Entry(model, app=self.app)
except ValueError:
pass
return s

def schedule_changed(self):
Expand All @@ -259,10 +254,8 @@ def schedule_changed(self):
# REPEATABLE-READ (default), then we won't see changes done by
# other transactions until the current transaction is
# committed (Issue #41).
try:
with contextlib.suppress(transaction.TransactionManagementError):
transaction.commit()
except transaction.TransactionManagementError:
pass # not in transaction management.

last, ts = self._last_timestamp, self.Changes.last_change()
except DatabaseError as exc:
Expand Down Expand Up @@ -325,7 +318,7 @@ def update_from_dict(self, mapping):
if entry.model.enabled:
s[name] = entry

except Exception as exc:
except Exception as exc: # noqa: PERF203
logger.exception(ADD_ENTRY_ERROR, name, exc, entry_fields)
self.schedule.update(s)

Expand Down
3 changes: 1 addition & 2 deletions django_celery_beat/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ def signals_connect():
"""Connect to signals."""
from django.db.models import signals

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

signals.pre_save.connect(
PeriodicTasks.changed, sender=PeriodicTask
Expand Down
8 changes: 4 additions & 4 deletions django_celery_beat/tzcrontab.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ def is_due(self, last_run_at):

# Needed to support pickling
def __repr__(self):
return """<crontab: {0._orig_minute} {0._orig_hour}
{0._orig_day_of_week} {0._orig_day_of_month}
{0._orig_month_of_year} (m/h/d/dM/MY), {0.tz}>
""".format(self)
return f"""<crontab: {self._orig_minute} {self._orig_hour}
{self._orig_day_of_week} {self._orig_day_of_month}
{self._orig_month_of_year} (m/h/d/dM/MY), {self.tz}>
"""

def __reduce__(self):
return (self.__class__, (self._orig_minute,
Expand Down
5 changes: 2 additions & 3 deletions django_celery_beat/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,9 @@ def make_aware(value):
# then convert to the Django configured timezone.
default_tz = timezone.get_default_timezone()
value = timezone.localtime(value, default_tz)
else:
elif timezone.is_naive(value):
# naive datetimes are assumed to be in local timezone.
if timezone.is_naive(value):
value = timezone.make_aware(value, timezone.get_default_timezone())
value = timezone.make_aware(value, timezone.get_default_timezone())
return value


Expand Down
4 changes: 2 additions & 2 deletions django_celery_beat/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self, *args):
def validate(cls, *args):
try:
cls(*args)
except Exception as e:
except Exception as e: # noqa: BLE001
raise ValueError(e)


Expand Down Expand Up @@ -59,7 +59,7 @@ def parse(self, value):
self.dangling = 0
self.vto = self.slice.parse_value(vto, sunday=6)
if self.vto < self.vfrom:
raise ValueError("Bad range '{0.vfrom}-{0.vto}'".format(self))
raise ValueError(f"Bad range '{self.vfrom}-{self.vto}'")
elif value == '*':
self.all()
else:
Expand Down
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import os
import os # noqa: INP001

from sphinx_celery import conf

Expand Down
Loading