Skip to content

Commit

Permalink
Merge pull request DjangoGirls#923 from marksweb/ci/ruff
Browse files Browse the repository at this point in the history
feat: Add ruff and fix issues
  • Loading branch information
amakarudze committed Dec 31, 2023
2 parents 0632a98 + 44a4b34 commit 2e328a2
Show file tree
Hide file tree
Showing 51 changed files with 343 additions and 188 deletions.
1 change: 0 additions & 1 deletion .github/workflows/django.yml
Original file line number Diff line number Diff line change
Expand Up @@ -60,4 +60,3 @@ jobs:
py.test --cov
env:
POSTGRES_PASSWORD: postgres

15 changes: 0 additions & 15 deletions .github/workflows/flake8.yml

This file was deleted.

30 changes: 30 additions & 0 deletions .github/workflows/ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: CI

on:
push:
branches:
- main
pull_request:
workflow_dispatch:

concurrency:
group: ${{ github.workflow }}-${{ github.ref_name }}-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: true

jobs:
ruff:
name: ruff
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.10"
cache: 'pip'
- run: |
python -m pip install --upgrade pip
pip install ruff
- name: Run Ruff
run: ruff .
13 changes: 4 additions & 9 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,19 +35,14 @@ repos:
"--ignore-init-module-imports",
]
files: \.py$
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
name: isort
entry: bash -c 'isort "$@"; git add -u;' --
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
entry: bash -c 'black "$@"; git add -u;' --
language_version: python3.10
- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: "v0.0.280"
hooks:
- id: flake8
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
2 changes: 1 addition & 1 deletion applications/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def lookups(self, request, queryset):
qs = Form.objects.all()
if not request.user.is_superuser:
qs = qs.filter(event__team__in=[request.user])
return map(lambda x: (x.id, str(x)), qs)
return map(lambda x: (x.id, str(x)), qs) # noqa: C417

def queryset(self, request, queryset):
if self.value():
Expand Down
6 changes: 3 additions & 3 deletions applications/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def save(self, *args, **kwargs):
else:
application.newsletter_optin = False

value = ", ".join(value) if type(value) == list else value
value = ", ".join(value) if isinstance(value, list) else value

if question:
answers.append(Answer(question=question, answer=value))
Expand Down Expand Up @@ -96,9 +96,9 @@ def save(self, *args, **kwargs):
],
)
msg.content_subtype = "html"
try:
try: # noqa: SIM105
msg.send()
except:
except: # noqa: E722
# TODO: what should we do when sending fails?
pass

Expand Down
17 changes: 12 additions & 5 deletions applications/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def __str__(self):
return f"Application form for {self.event.name}"

def save(self, *args, **kwargs):
is_form_new = False if self.pk else True
is_form_new = not self.pk
super().save(*args, **kwargs)

if is_form_new:
Expand Down Expand Up @@ -159,6 +159,9 @@ class Meta:
)
]

def __str__(self):
return str(self.pk)

def save(self, *args, **kwargs):
if self.pk is None:
current_max = Application.objects.filter(form=self.form).aggregate(models.Max("number"))["number__max"]
Expand Down Expand Up @@ -231,9 +234,6 @@ def is_scored_by_user(self, user):
"""
return self.scores.filter(user=user, score__gt=0).exists()

def __str__(self):
return str(self.pk)


class Answer(models.Model):
application = models.ForeignKey(Application, null=False, blank=False, on_delete=models.deletion.PROTECT)
Expand All @@ -243,6 +243,9 @@ class Answer(models.Model):
class Meta:
ordering = ("question__order",)

def __str__(self):
return f"{self.application} - {self.question}"


class Score(models.Model):
"""
Expand All @@ -264,6 +267,9 @@ class Meta:
"application",
)

def __str__(self):
return f"{self.user} - {self.application}. Score {self.score}"


class Email(models.Model):
form = models.ForeignKey(Form, on_delete=models.deletion.PROTECT)
Expand Down Expand Up @@ -326,10 +332,11 @@ def send(self):

msg = EmailMessage(self.subject, body, self.sent_from, [recipient.email])
msg.content_subtype = "html"
# TODO: What's the possible exception here? Catch specifics
try:
msg.send()
successfuly_sent.append(recipient.email)
except: # TODO: What's the possible exception here? Catch specifics
except: # noqa: E722
failed_to_sent.append(recipient.email)

self.sent = timezone.now()
Expand Down
2 changes: 1 addition & 1 deletion applications/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def get_applications_for_event(event, state=None, rsvp_status=None, order=None,
applications = applications.filter(state__in=state)

if order:
is_reversed = True if order[0] == "-" else False
is_reversed = order[0] == "-"
order = order[1:] if order[0] == "-" else order
if order == "average_score":
# here is an exception for the average_score, because we also want to get
Expand Down
3 changes: 2 additions & 1 deletion applications/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,9 +109,10 @@ def applications_csv(request, page_url):
rsvp_status = request.GET.getlist("rsvp_status", None)
event = get_event(page_url, request.user.is_authenticated, False)
order = request.GET.get("order", None)
# TODO: what's the exception here?
try:
applications = get_applications_for_event(event, state, rsvp_status, order)
except: # TODO: what's the exception here?
except: # noqa: E722
return redirect("core:event", page_url=page_url)
response = HttpResponse(content_type="text/csv")
response["Content-Disposition"] = f'attachment; filename="{page_url}.csv"'
Expand Down
21 changes: 12 additions & 9 deletions coach/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,18 @@ class Meta:
def __str__(self):
return self.name

def save(self, *args, **kwargs):
try:
super().save(*args, **kwargs)
except IntegrityError as err:
raise ValidationError(
{
"name": _("Coach with name %s and twitter_handle %s already exists.")
% (self.name, self.twitter_handle)
}
) from err
return self

def photo_display_for_admin(self):
coach_change_url = reverse("admin:coach_coach_change", args=[self.id])
return f"""
Expand All @@ -45,12 +57,3 @@ def photo_url(self):
return DEFAULT_COACH_PHOTO

return DEFAULT_COACH_PHOTO

def save(self, *args, **kwargs):
try:
super().save(*args, **kwargs)
except IntegrityError:
raise ValidationError(
{"name": _(f"Coach with name {self.name} and twitter_handle {self.twitter_handle} " "already exists.")}
)
return self
15 changes: 7 additions & 8 deletions core/admin/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ def has_stats(self, obj):
def full_url(self, obj):
url = reverse("core:event", kwargs={"page_url": obj.page_url})
url = f"https://djangogirls.org{url}"
return mark_safe('<a href="{url}">{url}</a>'.format(url=url))
return mark_safe(f'<a href="{url}">{url}</a>')

def get_readonly_fields(self, request, obj=None):
fields = set(self.readonly_fields) | {"full_url"}
Expand Down Expand Up @@ -228,13 +228,12 @@ def view_manage_organizers(self, request):
user = User.objects.get(id=request.GET["remove"])
if user == request.user:
messages.error(request, _("You cannot remove yourself from a team."))
else:
if user in event.team.all():
event.team.remove(user)
messages.success(
request, _("Organizer %(user_name)s has been removed") % {"user_name": user.get_full_name()}
)
return HttpResponseRedirect(reverse("admin:core_event_manage_organizers") + f"?event_id={event.id}")
elif user in event.team.all():
event.team.remove(user)
messages.success(
request, _("Organizer %(user_name)s has been removed") % {"user_name": user.get_full_name()}
)
return HttpResponseRedirect(reverse("admin:core_event_manage_organizers") + f"?event_id={event.id}")

return render(
request,
Expand Down
2 changes: 1 addition & 1 deletion core/admin/filters/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def lookups(self, request, queryset):
qs = Event.objects.all()
if not request.user.is_superuser:
qs = qs.filter(team__in=[request.user])
return map(lambda x: (x.id, str(x)), qs)
return map(lambda x: (x.id, str(x)), qs) # noqa: C417

def queryset(self, request, queryset):
if self.value():
Expand Down
1 change: 0 additions & 1 deletion core/context_processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ def statistics(request):
"attendees_sum": attendees["attendees"],
"applicants_sum": attendees["applicants"],
"organizers_count": organizers.count(),
"bronze": bronze,
"diamond": diamond,
"gold": gold,
"platinum": platinum,
Expand Down
2 changes: 1 addition & 1 deletion core/default_eventpage_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
def get_random_photo(section):
if section in DEFAULT_BACKGROUND_PHOTOS:
photos = DEFAULT_BACKGROUND_PHOTOS[section]
return UploadedFile(open(photos[random.randint(0, len(photos) - 1)], "rb"))
return UploadedFile(open(photos[random.randint(0, len(photos) - 1)], "rb")) # noqa: SIM115
return None


Expand Down
6 changes: 2 additions & 4 deletions core/deploy_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@ def copy_event(previous_event, event_date):

previous_event_id = previous_event.pk
# If event is already Django Girls City #2, remove #2 from it
if "#" in previous_event.name:
generic_event_name = previous_event.name.split(" #")[0]
else:
generic_event_name = previous_event.name

generic_event_name = previous_event.name.split(" #")[0] if "#" in previous_event.name else previous_event.name

previous_event_name = f"{generic_event_name} #{number}"
event_name = f"{generic_event_name} #{number + 1}"
Expand Down
8 changes: 4 additions & 4 deletions core/management/commands/backup_postgres_to_s3.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ class Command(BaseCommand):
help = "Backs up PostgreSQL database to AWS S3"

def handle(self, *args, **options):
AWS_ACCESS_KEY_ID = os.environ.get("AWS_S3_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_S3_SECRET_ACCESS_KEY")
AWS_REGION_NAME = os.environ.get("AWS_S3_REGION_NAME")
AWS_BUCKET_NAME = os.environ.get("AWS_S3_BUCKET_NAME")
AWS_ACCESS_KEY_ID = os.environ.get("AWS_S3_ACCESS_KEY_ID") # noqa: N806
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_S3_SECRET_ACCESS_KEY") # noqa: N806
AWS_REGION_NAME = os.environ.get("AWS_S3_REGION_NAME") # noqa: N806
AWS_BUCKET_NAME = os.environ.get("AWS_S3_BUCKET_NAME") # noqa: N806

session = Session(
aws_access_key_id=AWS_ACCESS_KEY_ID,
Expand Down
2 changes: 1 addition & 1 deletion core/management/commands/handle_emails.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def send_event_emails(
if ignore_approximate_events and event.date_is_approximate:
continue

recipients = list(set([event.email] + list(event.team.all().values_list("email", flat=True))))
recipients = list(set([event.email] + list(event.team.all().values_list("email", flat=True)))) # noqa: RUF005
context = {
"event": event,
"settings": settings,
Expand Down
2 changes: 1 addition & 1 deletion core/management_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def brag_on_slack_bang(city, country, team):
text = (
f":django_pony: :zap: Woohoo! :tada: New Django Girls alert! "
f"Welcome Django Girls {city}, {country}. "
f"Congrats {', '.join(['{} {}'.format(x.first_name, x.last_name) for x in team])}!"
f"Congrats {', '.join([f'{x.first_name} {x.last_name}' for x in team])}!"
)

post_message_to_slack("#general", text)
30 changes: 15 additions & 15 deletions core/models/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,21 +76,25 @@ class Event(models.Model):
blank=True,
)

objects = EventManager()
all_objects = models.Manager() # This includes deleted objects

# Flags for email states
thank_you_email_sent = models.DateTimeField(null=True, blank=True)
submit_information_email_sent = models.DateTimeField(null=True, blank=True)
offer_help_email_sent = models.DateTimeField(null=True, blank=True)

def __str__(self):
return f"{self.name}, {self.date}"
all_objects = models.Manager() # This includes deleted objects
objects = EventManager()

class Meta:
ordering = ("-date",)
verbose_name_plural = "List of events"

def __str__(self):
return f"{self.name}, {self.date}"

def delete(self, using=None, keep_parents=False):
self.is_deleted = True
self.save()

def is_upcoming(self):
now = timezone.now()
now = ApproximateDate(year=now.year, month=now.month, day=now.day)
Expand Down Expand Up @@ -158,10 +162,6 @@ def has_organizer(self, user):
def has_stats(self):
return bool(self.applicants_count and self.attendees_count)

def delete(self, using=None, keep_parents=False):
self.is_deleted = True
self.save()

def add_default_content(self):
"""Populate EventPageContent with default layout"""
data = get_default_eventpage_data()
Expand Down Expand Up @@ -265,23 +265,23 @@ class EventPageContent(models.Model):
coaches = models.ManyToManyField(to="coach.Coach", verbose_name="Coaches")
sponsors = models.ManyToManyField(to="sponsor.Sponsor", verbose_name="Sponsors")

def __str__(self):
return f"{self.name} at {self.event}"

class Meta:
ordering = ("position",)
verbose_name = "Website Content"

def __str__(self):
return f"{self.name} at {self.event}"


class EventPageMenu(models.Model):
event = models.ForeignKey(to=Event, null=False, blank=False, related_name="menu", on_delete=models.deletion.CASCADE)
title = models.CharField(max_length=255)
url = models.CharField(max_length=255, help_text="http://djangogirls.org/city/<the value you enter here>")
position = models.PositiveIntegerField(help_text="Order of menu")

def __str__(self):
return self.title

class Meta:
ordering = ("position",)
verbose_name = "Website Menu"

def __str__(self):
return self.title
Loading

0 comments on commit 2e328a2

Please sign in to comment.