Skip to content

Commit

Permalink
Make project ruff compliant
Browse files Browse the repository at this point in the history
- Majority of fixes done with ruff --fix option
- Some manual intervention and sanity checks
- Exlucdes one fix addressed in later commit
  • Loading branch information
Bekabyx committed Jul 31, 2023
1 parent b50e75d commit 57eb4e4
Show file tree
Hide file tree
Showing 162 changed files with 447 additions and 544 deletions.
1 change: 1 addition & 0 deletions .circleci/tests/test_deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ def get_output_value(stack, output_key):
if output["OutputKey"] == output_key:
# Cloudformation Outputs have unique per-stack names
return output["OutputValue"]
return None


@pytest.fixture
Expand Down
5 changes: 1 addition & 4 deletions deploy/after_install/write_envfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

import boto3


client = boto3.client("ssm", region_name="eu-west-2")


Expand All @@ -33,9 +32,7 @@ def get_parameter_store_vars() -> Dict:

def get_deploy_vars() -> Dict:
with open(Path(__file__).parents[1] / "deploy-env-vars.json") as f:
deploy_vars = json.loads(f.read())

return deploy_vars
return json.loads(f.read())


def write_parameters_to_envfile() -> None:
Expand Down
3 changes: 2 additions & 1 deletion deploy/create_deployment.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import os
import boto3
import time

import boto3

session = boto3.Session()


Expand Down
9 changes: 5 additions & 4 deletions deploy/create_deployment_group.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import os
import time

import boto3
from botocore.exceptions import ClientError
import time

session = boto3.Session()

Expand Down Expand Up @@ -87,9 +88,9 @@ def create_default_asg():
for asg in client.describe_auto_scaling_groups()["AutoScalingGroups"]
]
if "default" in existing_asgs:
return
return None

response = client.create_auto_scaling_group(
return client.create_auto_scaling_group(
AutoScalingGroupName="default",
AvailabilityZones=[
"eu-west-2a",
Expand Down Expand Up @@ -117,7 +118,6 @@ def create_default_asg():
],
VPCZoneIdentifier=",".join(subnet_ids),
)
return response


def get_service_role():
Expand Down Expand Up @@ -191,6 +191,7 @@ def main():
# step as the instance needs to have initialised and be in ready state
# before code deploy can create a start deployment
time.sleep(60)
return None


if __name__ == "__main__":
Expand Down
5 changes: 3 additions & 2 deletions deploy/update_auto_scaling_group.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from collections import defaultdict
import os
import boto3
import time
from collections import defaultdict

import boto3

client = boto3.client("autoscaling")

Expand All @@ -13,6 +13,7 @@ def _filter_by_code_deploy_tag(asg):
"""
for tag in asg["Tags"]:
return tag["Key"] == "CodeDeploy"
return None


def get_latest_code_deploy_tagged_asg():
Expand Down
1 change: 1 addition & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python
import os
import sys

import dotenv

if __name__ == "__main__":
Expand Down
1 change: 1 addition & 0 deletions wcivf/apps/api/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ def has_object_permission(self, request, view, obj):
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
return False
7 changes: 4 additions & 3 deletions wcivf/apps/api/serializers.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from rest_framework import serializers

from elections.models import VotingSystem
from leaflets.api.serializers import LeafletSerializer
from people.models import Person, PersonPost
from parties.models import Party
from people.models import Person, PersonPost
from rest_framework import serializers


class PersonSerializer(serializers.ModelSerializer):
Expand Down Expand Up @@ -33,6 +32,7 @@ def get_leaflets(self, obj: Person):
leaflets = obj.ordered_leaflets[:4]
if leaflets:
return LeafletSerializer(leaflets, many=True, read_only=True).data
return None


class PartySerializer(serializers.HyperlinkedModelSerializer):
Expand Down Expand Up @@ -78,6 +78,7 @@ def get_previous_party_affiliations(self, obj: PersonPost):
parties = obj.previous_party_affiliations.all()
if parties:
return PartySerializer(parties, many=True, read_only=True).data
return None


class VotingSystemSerializer(serializers.ModelSerializer):
Expand Down
15 changes: 7 additions & 8 deletions wcivf/apps/api/tests/test_api.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
from django.core.cache import cache
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
import vcr

from people.tests.factories import PersonFactory, PersonPostFactory
from parties.tests.factories import PartyFactory
from django.core.cache import cache
from elections.tests.factories import (
ElectionFactory,
PostFactory,
PostElectionFactory,
PostFactory,
)
from parties.tests.factories import PartyFactory
from people.tests.factories import PersonFactory, PersonPostFactory
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase


class TestAPIBasics(APITestCase):
Expand Down Expand Up @@ -133,4 +132,4 @@ def test_lock_status(self):
url = reverse("api:candidates-for-postcode-list")
req = self.client.get("{}?postcode=EC1A4EU".format(url))
assert req.status_code == 200
assert req.json()[0]["ballot_locked"] == True
assert req.json()[0]["ballot_locked"] is True
6 changes: 2 additions & 4 deletions wcivf/apps/api/urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from django.urls import path, include

from rest_framework import routers

from api import views
from django.urls import include, path
from rest_framework import routers

router = routers.DefaultRouter()

Expand Down
19 changes: 8 additions & 11 deletions wcivf/apps/api/views.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import abc

from rest_framework import viewsets
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.views import APIView

from django.conf import settings
from django.utils.http import urlencode

from api import serializers
from api.serializers import VotingSystemSerializer
from core.helpers import clean_postcode
from django.conf import settings
from django.utils.http import urlencode
from elections.models import InvalidPostcodeError, PostElection
from elections.views import mixins
from elections.models import PostElection, InvalidPostcodeError
from hustings.api.serializers import HustingSerializer
from people.models import Person
from rest_framework import viewsets
from rest_framework.exceptions import APIException
from rest_framework.response import Response
from rest_framework.views import APIView


class PostcodeNotProvided(APIException):
Expand Down Expand Up @@ -160,8 +158,7 @@ def get_ballots(self, request):
pes = pes.modified_gt_with_related(date=modified_gt)
else:
pes = pes.order_by(*ordering)
ret = {"ballots": pes[:100]}
return ret
return {"ballots": pes[:100]}


class LastUpdatedView(APIView):
Expand Down
2 changes: 1 addition & 1 deletion wcivf/apps/core/context_processors.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from core.helpers import clean_postcode
from django.conf import settings

from core.helpers import clean_postcode
from .forms import PostcodeLookupForm


Expand Down
1 change: 0 additions & 1 deletion wcivf/apps/core/forms.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django import forms
from django.utils.translation import gettext_lazy as _

from localflavor.gb.forms import GBPostcodeField


Expand Down
5 changes: 2 additions & 3 deletions wcivf/apps/core/helpers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import json
import re
from contextlib import contextmanager
from datetime import datetime, timedelta
from urllib.parse import urlparse
import json


@contextmanager
Expand Down Expand Up @@ -46,8 +46,7 @@ def clean_postcode(postcode):
postcode = postcode.replace("+", "")
incode_pattern = "[0-9][ABD-HJLNP-UW-Z]{2}"
space_regex = re.compile(r" *(%s)$" % incode_pattern)
postcode = space_regex.sub(r" \1", postcode.upper())
return postcode
return space_regex.sub(r" \1", postcode.upper())


def twitter_username(url):
Expand Down
22 changes: 10 additions & 12 deletions wcivf/apps/core/management/commands/init_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@

from django.conf import settings
from django.core.cache import cache
from django.core.management.base import BaseCommand
from django.core.management import call_command

from django.core.management.base import BaseCommand
from elections.constants import (
PEOPLE_FOR_BALLOT_KEY_FMT,
POSTCODE_TO_BALLOT_KEY_FMT,
POLLING_STATIONS_KEY_FMT,
POSTCODE_TO_BALLOT_KEY_FMT,
)


Expand Down Expand Up @@ -36,15 +35,14 @@ def handle(self, **options):
print(" ".join(command))
call_command(*command)

if options["full"]:
# Delete the cache on a full import
if hasattr(cache, "delete_pattern"):
for fmt in (
POLLING_STATIONS_KEY_FMT,
POSTCODE_TO_BALLOT_KEY_FMT,
PEOPLE_FOR_BALLOT_KEY_FMT,
):
cache.delete_pattern(fmt.format("*"))
# Delete the cache on a full import
if options["full"] and hasattr(cache, "delete_pattern"):
for fmt in (
POLLING_STATIONS_KEY_FMT,
POSTCODE_TO_BALLOT_KEY_FMT,
PEOPLE_FOR_BALLOT_KEY_FMT,
):
cache.delete_pattern(fmt.format("*"))

# Unset dirty file if it exists
if getattr(settings, "CHECK_HOST_DIRTY", False):
Expand Down
3 changes: 1 addition & 2 deletions wcivf/apps/core/management/commands/process_log_queue.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.core.management.base import BaseCommand

from core.models import write_logged_postcodes
from django.core.management.base import BaseCommand


class Command(BaseCommand):
Expand Down
2 changes: 1 addition & 1 deletion wcivf/apps/core/management/commands/setup_django_site.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
Hack because Django makes it hard to use data migrations to do this :/
"""

from django.core.management.base import BaseCommand
from django.contrib.sites.models import Site
from django.core.management.base import BaseCommand


class Command(BaseCommand):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
from django.core.management.base import BaseCommand


from django.db import connection

from elections.models import VotingSystem


Expand Down
3 changes: 1 addition & 2 deletions wcivf/apps/core/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ def __init__(self, get_response):

def __call__(self, request):
self.process_request(request)
response = self.get_response(request)
return response
return self.get_response(request)

def process_request(self, request):
def _get_value_from_req(key):
Expand Down
2 changes: 1 addition & 1 deletion wcivf/apps/core/migrations/0001_initial.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
# Generated by Django 1.9.4 on 2016-04-14 16:31
from __future__ import unicode_literals

from django.db import migrations, models
import django_extensions.db.fields
from django.db import migrations, models


class Migration(migrations.Migration):
Expand Down
2 changes: 1 addition & 1 deletion wcivf/apps/core/mixins.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import csv
import requests

import requests
from elections.models import PostElection


Expand Down
6 changes: 3 additions & 3 deletions wcivf/apps/core/models.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import json

import redis
from django.conf import settings
from django.utils import timezone
from django.db import models

from django.utils import timezone
from django_extensions.db.models import TimeStampedModel
import redis


class LoggedPostcode(TimeStampedModel):
Expand Down Expand Up @@ -33,6 +32,7 @@ def log_postcode(log_dict, blocking=False):

value = json.dumps(log_dict)
red.zadd(key, {value: log_dict["created"]})
return None


def write_logged_postcodes():
Expand Down
3 changes: 1 addition & 2 deletions wcivf/apps/core/templatetags/markdown_filter.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import markdown
from django import template
from django.utils.safestring import mark_safe

import markdown

register = template.Library()


Expand Down
2 changes: 1 addition & 1 deletion wcivf/apps/core/tests/helpers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import shutil
from tempfile import mkdtemp

from django.test import TestCase, override_settings
from django.conf import settings
from django.test import TestCase, override_settings


@override_settings(
Expand Down
Loading

0 comments on commit 57eb4e4

Please sign in to comment.