diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 63a70cba..cf5af39a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -22,7 +22,13 @@ repos: args: [ '--remove' ] - repo: https://github.com/editorconfig-checker/editorconfig-checker.python - rev: 2.3.5 + rev: 2.3.54 hooks: - id: editorconfig-checker exclude: ^(LICENSE|allianceauth\/static\/css\/themes\/bootstrap-locals.less|allianceauth\/eveonline\/swagger.json|(.*.po)|(.*.mo)) + + - repo: https://github.com/asottile/pyupgrade + rev: v2.29.0 + hooks: + - id: pyupgrade + args: [ --py37-plus ] diff --git a/allianceauth/__init__.py b/allianceauth/__init__.py index 0c8c5e16..180fdcc5 100644 --- a/allianceauth/__init__.py +++ b/allianceauth/__init__.py @@ -4,5 +4,5 @@ __version__ = '2.9.0' __title__ = 'Alliance Auth' __url__ = 'https://gitlab.com/allianceauth/allianceauth' -NAME = '%s v%s' % (__title__, __version__) +NAME = f'{__title__} v{__version__}' default_app_config = 'allianceauth.apps.AllianceAuthConfig' diff --git a/allianceauth/analytics/models.py b/allianceauth/analytics/models.py index bc290162..29a0fd1d 100644 --- a/allianceauth/analytics/models.py +++ b/allianceauth/analytics/models.py @@ -16,7 +16,7 @@ class AnalyticsIdentifier(models.Model): raise ValidationError('There is can be only one \ AnalyticsIdentifier instance') self.pk = self.id = 1 # If this happens to be deleted and recreated, force it to be 1 - return super(AnalyticsIdentifier, self).save(*args, **kwargs) + return super().save(*args, **kwargs) class AnalyticsPath(models.Model): diff --git a/allianceauth/authentication/admin.py b/allianceauth/authentication/admin.py index b39623cf..66b19e63 100644 --- a/allianceauth/authentication/admin.py +++ b/allianceauth/authentication/admin.py @@ -36,8 +36,8 @@ def make_service_hooks_update_groups_action(service): for user in queryset: # queryset filtering doesn't work here? service.update_groups(user) - update_service_groups.__name__ = str('update_{}_groups'.format(slugify(service.name))) - update_service_groups.short_description = "Sync groups for selected {} accounts".format(service.title) + update_service_groups.__name__ = str(f'update_{slugify(service.name)}_groups') + update_service_groups.short_description = f"Sync groups for selected {service.title} accounts" return update_service_groups @@ -54,8 +54,8 @@ def make_service_hooks_sync_nickname_action(service): for user in queryset: # queryset filtering doesn't work here? service.sync_nickname(user) - sync_nickname.__name__ = str('sync_{}_nickname'.format(slugify(service.name))) - sync_nickname.short_description = "Sync nicknames for selected {} accounts".format(service.title) + sync_nickname.__name__ = str(f'sync_{slugify(service.name)}_nickname') + sync_nickname.short_description = f"Sync nicknames for selected {service.title} accounts" return sync_nickname @@ -194,7 +194,7 @@ class MainCorporationsFilter(admin.SimpleListFilter): .distinct()\ .order_by(Lower('corporation_name')) return tuple( - [(x['corporation_id'], x['corporation_name']) for x in qs] + (x['corporation_id'], x['corporation_name']) for x in qs ) def queryset(self, request, qs): @@ -228,7 +228,7 @@ class MainAllianceFilter(admin.SimpleListFilter): .distinct()\ .order_by(Lower('alliance_name')) return tuple( - [(x['alliance_id'], x['alliance_name']) for x in qs] + (x['alliance_id'], x['alliance_name']) for x in qs ) def queryset(self, request, qs): @@ -252,7 +252,7 @@ def update_main_character_model(modeladmin, request, queryset): modeladmin.message_user( request, - 'Update from ESI started for {} characters'.format(tasks_count) + f'Update from ESI started for {tasks_count} characters' ) @@ -369,7 +369,7 @@ class UserAdmin(BaseUserAdmin): _state.admin_order_field = 'profile__state' def _groups(self, obj): - my_groups = sorted([group.name for group in list(obj.groups.all())]) + my_groups = sorted(group.name for group in list(obj.groups.all())) return self._list_2_html_w_tooltips( my_groups, AUTHENTICATION_ADMIN_USERS_MAX_GROUPS ) @@ -455,7 +455,7 @@ class StateAdmin(admin.ModelAdmin): def has_delete_permission(self, request, obj=None): if obj == get_guest_state(): return False - return super(StateAdmin, self).has_delete_permission(request, obj=obj) + return super().has_delete_permission(request, obj=obj) def get_fieldsets(self, request, obj=None): if obj == get_guest_state(): @@ -464,7 +464,7 @@ class StateAdmin(admin.ModelAdmin): 'fields': ('permissions', 'priority'), }), ) - return super(StateAdmin, self).get_fieldsets(request, obj=obj) + return super().get_fieldsets(request, obj=obj) class BaseOwnershipAdmin(admin.ModelAdmin): diff --git a/allianceauth/authentication/apps.py b/allianceauth/authentication/apps.py index 10726de1..dd12e95d 100644 --- a/allianceauth/authentication/apps.py +++ b/allianceauth/authentication/apps.py @@ -7,6 +7,6 @@ class AuthenticationConfig(AppConfig): label = 'authentication' def ready(self): - super(AuthenticationConfig, self).ready() + super().ready() from allianceauth.authentication import checks, signals register(Tags.security)(checks.check_login_scopes_setting) diff --git a/allianceauth/authentication/backends.py b/allianceauth/authentication/backends.py index d0cecf4a..526950d9 100644 --- a/allianceauth/authentication/backends.py +++ b/allianceauth/authentication/backends.py @@ -36,17 +36,17 @@ class StateBackend(ModelBackend): try: ownership = CharacterOwnership.objects.get(character__character_id=token.character_id) if ownership.owner_hash == token.character_owner_hash: - logger.debug('Authenticating {0} by ownership of character {1}'.format(ownership.user, token.character_name)) + logger.debug(f'Authenticating {ownership.user} by ownership of character {token.character_name}') return ownership.user else: - logger.debug('{0} has changed ownership. Creating new user account.'.format(token.character_name)) + logger.debug(f'{token.character_name} has changed ownership. Creating new user account.') ownership.delete() return self.create_user(token) except CharacterOwnership.DoesNotExist: try: # insecure legacy main check for pre-sso registration auth installs profile = UserProfile.objects.get(main_character__character_id=token.character_id) - logger.debug('Authenticating {0} by their main character {1} without active ownership.'.format(profile.user, profile.main_character)) + logger.debug(f'Authenticating {profile.user} by their main character {profile.main_character} without active ownership.') # attach an ownership token.user = profile.user CharacterOwnership.objects.create_by_token(token) @@ -59,13 +59,13 @@ class StateBackend(ModelBackend): user = records[0].user token.user = user co = CharacterOwnership.objects.create_by_token(token) - logger.debug('Authenticating {0} by matching owner hash record of character {1}'.format(user, co.character)) + logger.debug(f'Authenticating {user} by matching owner hash record of character {co.character}') if not user.profile.main_character: # set this as their main by default if they have none user.profile.main_character = co.character user.profile.save() return user - logger.debug('Unable to authenticate character {0}. Creating new user.'.format(token.character_name)) + logger.debug(f'Unable to authenticate character {token.character_name}. Creating new user.') return self.create_user(token) def create_user(self, token): @@ -77,7 +77,7 @@ class StateBackend(ModelBackend): co = CharacterOwnership.objects.create_by_token(token) # assign ownership to this user user.profile.main_character = co.character # assign main character as token character user.profile.save() - logger.debug('Created new user {0}'.format(user)) + logger.debug(f'Created new user {user}') return user @staticmethod @@ -87,10 +87,10 @@ class StateBackend(ModelBackend): if User.objects.filter(username__startswith=name).exists(): u = User.objects.filter(username__startswith=name) num = len(u) - username = "%s_%s" % (name, num) + username = f"{name}_{num}" while u.filter(username=username).exists(): num += 1 - username = "%s_%s" % (name, num) + username = f"{name}_{num}" else: username = name return username diff --git a/allianceauth/authentication/management/commands/checkmains.py b/allianceauth/authentication/management/commands/checkmains.py index 6c4b7fb2..5605687b 100644 --- a/allianceauth/authentication/management/commands/checkmains.py +++ b/allianceauth/authentication/management/commands/checkmains.py @@ -11,10 +11,10 @@ class Command(BaseCommand): if profiles.exists(): for profile in profiles: self.stdout.write(self.style.ERROR( - '{0} does not have an ownership. Resetting user {1} main character.'.format(profile.main_character, + '{} does not have an ownership. Resetting user {} main character.'.format(profile.main_character, profile.user))) profile.main_character = None profile.save() - self.stdout.write(self.style.WARNING('Reset {0} main characters.'.format(profiles.count()))) + self.stdout.write(self.style.WARNING(f'Reset {profiles.count()} main characters.')) else: self.stdout.write(self.style.SUCCESS('All main characters have active ownership.')) diff --git a/allianceauth/authentication/managers.py b/allianceauth/authentication/managers.py index 3b2e8ed0..56256501 100755 --- a/allianceauth/authentication/managers.py +++ b/allianceauth/authentication/managers.py @@ -49,7 +49,7 @@ class StateQuerySet(QuerySet): for state in self: for profile in state.userprofile_set.all(): profile.assign_state(state=self.model.objects.exclude(pk=state.pk).get_for_user(profile.user)) - super(StateQuerySet, self).delete() + super().delete() class StateManager(Manager): diff --git a/allianceauth/authentication/migrations/0001_initial.py b/allianceauth/authentication/migrations/0001_initial.py index 3f9454e6..a7d3ff64 100644 --- a/allianceauth/authentication/migrations/0001_initial.py +++ b/allianceauth/authentication/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:38 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/authentication/migrations/0002_auto_20160907_1914.py b/allianceauth/authentication/migrations/0002_auto_20160907_1914.py index 8045e83e..f8ed8f1d 100644 --- a/allianceauth/authentication/migrations/0002_auto_20160907_1914.py +++ b/allianceauth/authentication/migrations/0002_auto_20160907_1914.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-07 19:14 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/authentication/migrations/0003_authservicesinfo_state.py b/allianceauth/authentication/migrations/0003_authservicesinfo_state.py index 9ac14c83..4da327a4 100644 --- a/allianceauth/authentication/migrations/0003_authservicesinfo_state.py +++ b/allianceauth/authentication/migrations/0003_authservicesinfo_state.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-09 20:29 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/authentication/migrations/0004_create_permissions.py b/allianceauth/authentication/migrations/0004_create_permissions.py index f63928fa..1f938d21 100644 --- a/allianceauth/authentication/migrations/0004_create_permissions.py +++ b/allianceauth/authentication/migrations/0004_create_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-09 23:19 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/authentication/migrations/0005_delete_perms.py b/allianceauth/authentication/migrations/0005_delete_perms.py index a674c95c..e870b8cd 100644 --- a/allianceauth/authentication/migrations/0005_delete_perms.py +++ b/allianceauth/authentication/migrations/0005_delete_perms.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-09 23:11 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/authentication/migrations/0006_auto_20160910_0542.py b/allianceauth/authentication/migrations/0006_auto_20160910_0542.py index 0bdd3498..03e1abb0 100644 --- a/allianceauth/authentication/migrations/0006_auto_20160910_0542.py +++ b/allianceauth/authentication/migrations/0006_auto_20160910_0542.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-10 05:42 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/authentication/migrations/0007_remove_authservicesinfo_is_blue.py b/allianceauth/authentication/migrations/0007_remove_authservicesinfo_is_blue.py index 8150d6b8..4eac80bb 100644 --- a/allianceauth/authentication/migrations/0007_remove_authservicesinfo_is_blue.py +++ b/allianceauth/authentication/migrations/0007_remove_authservicesinfo_is_blue.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-10 21:50 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/authentication/migrations/0008_set_state.py b/allianceauth/authentication/migrations/0008_set_state.py index 039409bd..7b55b97b 100644 --- a/allianceauth/authentication/migrations/0008_set_state.py +++ b/allianceauth/authentication/migrations/0008_set_state.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-12 13:04 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/authentication/migrations/0009_auto_20161021_0228.py b/allianceauth/authentication/migrations/0009_auto_20161021_0228.py index 853a01db..588169dc 100644 --- a/allianceauth/authentication/migrations/0009_auto_20161021_0228.py +++ b/allianceauth/authentication/migrations/0009_auto_20161021_0228.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-10-21 02:28 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/authentication/migrations/0010_only_one_authservicesinfo.py b/allianceauth/authentication/migrations/0010_only_one_authservicesinfo.py index b08e5283..a88bb301 100644 --- a/allianceauth/authentication/migrations/0010_only_one_authservicesinfo.py +++ b/allianceauth/authentication/migrations/0010_only_one_authservicesinfo.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2017-01-07 06:47 -from __future__ import unicode_literals from django.db import migrations @@ -9,7 +8,7 @@ def count_completed_fields(model): def forward(apps, schema_editor): # this ensures only one model exists per user AuthServicesInfo = apps.get_model('authentication', 'AuthServicesInfo') - users = set([a.user for a in AuthServicesInfo.objects.all()]) + users = {a.user for a in AuthServicesInfo.objects.all()} for u in users: auths = AuthServicesInfo.objects.filter(user=u) if auths.count() > 1: diff --git a/allianceauth/authentication/migrations/0011_authservicesinfo_user_onetoonefield.py b/allianceauth/authentication/migrations/0011_authservicesinfo_user_onetoonefield.py index ef694024..d12f2875 100644 --- a/allianceauth/authentication/migrations/0011_authservicesinfo_user_onetoonefield.py +++ b/allianceauth/authentication/migrations/0011_authservicesinfo_user_onetoonefield.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2017-01-07 07:11 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/authentication/migrations/0012_remove_add_delete_authservicesinfo_permissions.py b/allianceauth/authentication/migrations/0012_remove_add_delete_authservicesinfo_permissions.py index 208ea120..60fcc189 100644 --- a/allianceauth/authentication/migrations/0012_remove_add_delete_authservicesinfo_permissions.py +++ b/allianceauth/authentication/migrations/0012_remove_add_delete_authservicesinfo_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-01-12 00:59 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/authentication/migrations/0013_service_modules.py b/allianceauth/authentication/migrations/0013_service_modules.py index c7801dbd..f046905c 100644 --- a/allianceauth/authentication/migrations/0013_service_modules.py +++ b/allianceauth/authentication/migrations/0013_service_modules.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-11 23:14 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/authentication/migrations/0014_fleetup_permission.py b/allianceauth/authentication/migrations/0014_fleetup_permission.py index cfe60109..715d1b00 100644 --- a/allianceauth/authentication/migrations/0014_fleetup_permission.py +++ b/allianceauth/authentication/migrations/0014_fleetup_permission.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-09 23:19 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/authentication/migrations/0015_user_profiles.py b/allianceauth/authentication/migrations/0015_user_profiles.py index dccd1808..10ba691c 100644 --- a/allianceauth/authentication/migrations/0015_user_profiles.py +++ b/allianceauth/authentication/migrations/0015_user_profiles.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:09 -from __future__ import unicode_literals import allianceauth.authentication.models import django.db.models.deletion diff --git a/allianceauth/authentication/migrations/0017_remove_fleetup_permission.py b/allianceauth/authentication/migrations/0017_remove_fleetup_permission.py index f83b7a6a..38821f41 100644 --- a/allianceauth/authentication/migrations/0017_remove_fleetup_permission.py +++ b/allianceauth/authentication/migrations/0017_remove_fleetup_permission.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - from django.db import migrations diff --git a/allianceauth/authentication/models.py b/allianceauth/authentication/models.py index e95fe031..8ca6cef6 100755 --- a/allianceauth/authentication/models.py +++ b/allianceauth/authentication/models.py @@ -39,7 +39,7 @@ class State(models.Model): with transaction.atomic(): for profile in self.userprofile_set.all(): profile.assign_state(state=State.objects.exclude(pk=self.pk).get_for_user(profile.user)) - super(State, self).delete(**kwargs) + super().delete(**kwargs) def get_guest_state(): @@ -67,7 +67,7 @@ class UserProfile(models.Model): if self.state != state: self.state = state if commit: - logger.info('Updating {} state to {}'.format(self.user, self.state)) + logger.info(f'Updating {self.user} state to {self.state}') self.save(update_fields=['state']) notify( self.user, @@ -102,7 +102,7 @@ class CharacterOwnership(models.Model): objects = CharacterOwnershipManager() def __str__(self): - return "%s: %s" % (self.user, self.character) + return f"{self.user}: {self.character}" class OwnershipRecord(models.Model): @@ -115,4 +115,4 @@ class OwnershipRecord(models.Model): ordering = ['-created'] def __str__(self): - return "%s: %s on %s" % (self.user, self.character, self.created) + return f"{self.user}: {self.character} on {self.created}" diff --git a/allianceauth/authentication/signals.py b/allianceauth/authentication/signals.py index 335a1c00..0f65518d 100644 --- a/allianceauth/authentication/signals.py +++ b/allianceauth/authentication/signals.py @@ -29,27 +29,27 @@ def trigger_state_check(state): @receiver(m2m_changed, sender=State.member_characters.through) def state_member_characters_changed(sender, instance, action, *args, **kwargs): if action.startswith('post_'): - logger.debug('State {} member characters changed. Re-evaluating membership.'.format(instance)) + logger.debug(f'State {instance} member characters changed. Re-evaluating membership.') trigger_state_check(instance) @receiver(m2m_changed, sender=State.member_corporations.through) def state_member_corporations_changed(sender, instance, action, *args, **kwargs): if action.startswith('post_'): - logger.debug('State {} member corporations changed. Re-evaluating membership.'.format(instance)) + logger.debug(f'State {instance} member corporations changed. Re-evaluating membership.') trigger_state_check(instance) @receiver(m2m_changed, sender=State.member_alliances.through) def state_member_alliances_changed(sender, instance, action, *args, **kwargs): if action.startswith('post_'): - logger.debug('State {} member alliances changed. Re-evaluating membership.'.format(instance)) + logger.debug(f'State {instance} member alliances changed. Re-evaluating membership.') trigger_state_check(instance) @receiver(post_save, sender=State) def state_saved(sender, instance, *args, **kwargs): - logger.debug('State {} saved. Re-evaluating membership.'.format(instance)) + logger.debug(f'State {instance} saved. Re-evaluating membership.') trigger_state_check(instance) @@ -60,7 +60,7 @@ def reassess_on_profile_save(sender, instance, created, *args, **kwargs): if not created: update_fields = kwargs.pop('update_fields', []) or [] if 'state' not in update_fields: - logger.debug('Profile for {} saved without state change. Re-evaluating state.'.format(instance.user)) + logger.debug(f'Profile for {instance.user} saved without state change. Re-evaluating state.') instance.assign_state() @@ -68,14 +68,14 @@ def reassess_on_profile_save(sender, instance, created, *args, **kwargs): def create_required_models(sender, instance, created, *args, **kwargs): # ensure all users have a model if created: - logger.debug('User {} created. Creating default UserProfile.'.format(instance)) + logger.debug(f'User {instance} created. Creating default UserProfile.') UserProfile.objects.get_or_create(user=instance) @receiver(post_save, sender=Token) def record_character_ownership(sender, instance, created, *args, **kwargs): if created: - logger.debug('New token for {0} character {1} saved. Evaluating ownership.'.format(instance.user, instance.character_name)) + logger.debug(f'New token for {instance.user} character {instance.character_name} saved. Evaluating ownership.') if instance.user: query = Q(owner_hash=instance.character_owner_hash) & Q(user=instance.user) else: @@ -84,13 +84,13 @@ def record_character_ownership(sender, instance, created, *args, **kwargs): CharacterOwnership.objects.filter(character__character_id=instance.character_id).exclude(query).delete() # create character if needed if EveCharacter.objects.filter(character_id=instance.character_id).exists() is False: - logger.debug('Token is for a new character. Creating model for {0} ({1})'.format(instance.character_name, instance.character_id)) + logger.debug(f'Token is for a new character. Creating model for {instance.character_name} ({instance.character_id})') EveCharacter.objects.create_character(instance.character_id) char = EveCharacter.objects.get(character_id=instance.character_id) # check if we need to create ownership if instance.user and not CharacterOwnership.objects.filter( character__character_id=instance.character_id).exists(): - logger.debug("Character {0} is not yet owned. Assigning ownership to {1}".format(instance.character_name, instance.user)) + logger.debug(f"Character {instance.character_name} is not yet owned. Assigning ownership to {instance.user}") CharacterOwnership.objects.update_or_create(character=char, defaults={'owner_hash': instance.character_owner_hash, 'user': instance.user}) @@ -98,7 +98,7 @@ def record_character_ownership(sender, instance, created, *args, **kwargs): def validate_main_character(sender, instance, *args, **kwargs): try: if instance.user.profile.main_character == instance.character: - logger.info("Ownership of a main character {0} has been revoked. Resetting {1} main character.".format( + logger.info("Ownership of a main character {} has been revoked. Resetting {} main character.".format( instance.character, instance.user)) # clear main character as user no longer owns them instance.user.profile.main_character = None @@ -111,7 +111,7 @@ def validate_main_character(sender, instance, *args, **kwargs): @receiver(post_delete, sender=Token) def validate_ownership(sender, instance, *args, **kwargs): if not Token.objects.filter(character_owner_hash=instance.character_owner_hash).filter(refresh_token__isnull=False).exists(): - logger.info("No remaining tokens to validate ownership of character {0}. Revoking ownership.".format(instance.character_name)) + logger.info(f"No remaining tokens to validate ownership of character {instance.character_name}. Revoking ownership.") CharacterOwnership.objects.filter(owner_hash=instance.character_owner_hash).delete() @@ -122,11 +122,11 @@ def assign_state_on_active_change(sender, instance, *args, **kwargs): old_instance = User.objects.get(pk=instance.pk) if old_instance.is_active != instance.is_active: if instance.is_active: - logger.debug("User {0} has been activated. Assigning state.".format(instance)) + logger.debug(f"User {instance} has been activated. Assigning state.") instance.profile.assign_state() else: logger.debug( - "User {0} has been deactivated. Revoking state and assigning to guest state.".format(instance)) + f"User {instance} has been deactivated. Revoking state and assigning to guest state.") instance.profile.state = get_guest_state() instance.profile.save(update_fields=['state']) @@ -135,10 +135,10 @@ def assign_state_on_active_change(sender, instance, *args, **kwargs): def check_state_on_character_update(sender, instance, *args, **kwargs): # if this is a main character updating, check that user's state try: - logger.debug("Character {0} has been saved. Assessing owner's state for changes.".format(instance)) + logger.debug(f"Character {instance} has been saved. Assessing owner's state for changes.") instance.userprofile.assign_state() except UserProfile.DoesNotExist: - logger.debug("Character {0} is not a main character. No state assessment required.".format(instance)) + logger.debug(f"Character {instance} is not a main character. No state assessment required.") pass @@ -148,7 +148,7 @@ def ownership_record_creation(sender, instance, created, *args, **kwargs): records = OwnershipRecord.objects.filter(owner_hash=instance.owner_hash).filter(character=instance.character) if records.exists(): if records[0].user == instance.user: # most recent record is sorted first - logger.debug("Already have ownership record of {0} by user {1}".format(instance.character, instance.user)) + logger.debug(f"Already have ownership record of {instance.character} by user {instance.user}") return - logger.info("Character {0} has a new owner {1}. Creating ownership record.".format(instance.character, instance.user)) + logger.info(f"Character {instance.character} has a new owner {instance.user}. Creating ownership record.") OwnershipRecord.objects.create(user=instance.user, character=instance.character, owner_hash=instance.owner_hash) diff --git a/allianceauth/authentication/tasks.py b/allianceauth/authentication/tasks.py index 3a9064f1..eaf3c59a 100644 --- a/allianceauth/authentication/tasks.py +++ b/allianceauth/authentication/tasks.py @@ -22,13 +22,13 @@ def check_character_ownership(owner_hash): continue except (KeyError, IncompleteResponseError): # We can't validate the hash hasn't changed but also can't assume it has. Abort for now. - logger.warning("Failed to validate owner hash of {0} due to problems contacting SSO servers.".format( + logger.warning("Failed to validate owner hash of {} due to problems contacting SSO servers.".format( tokens[0].character_name)) break if not t.character_owner_hash == old_hash: logger.info( - 'Character %s has changed ownership. Revoking %s tokens.' % (t.character_name, tokens.count())) + f'Character {t.character_name} has changed ownership. Revoking {tokens.count()} tokens.') tokens.delete() break diff --git a/allianceauth/authentication/tests/test_admin.py b/allianceauth/authentication/tests/test_admin.py index 41d5a88b..80ed52b5 100644 --- a/allianceauth/authentication/tests/test_admin.py +++ b/allianceauth/authentication/tests/test_admin.py @@ -36,7 +36,7 @@ from . import get_admin_change_view_url, get_admin_search_url MODULE_PATH = 'allianceauth.authentication.admin' -class MockRequest(object): +class MockRequest: def __init__(self, user=None): self.user = user @@ -188,7 +188,7 @@ def make_generic_search_request(ModelClass: type, search_term: str): c = Client() c.login(username='superuser', password='secret') return c.get( - '%s?q=%s' % (get_admin_search_url(ModelClass), quote(search_term)) + f'{get_admin_search_url(ModelClass)}?q={quote(search_term)}' ) diff --git a/allianceauth/authentication/tests/test_backend.py b/allianceauth/authentication/tests/test_backend.py index 212cae46..ed984521 100644 --- a/allianceauth/authentication/tests/test_backend.py +++ b/allianceauth/authentication/tests/test_backend.py @@ -114,12 +114,12 @@ class TestAuthenticate(TestCase): def test_authenticate_main_character(self): t = Token(character_id=self.main_character.character_id, character_owner_hash='1') user = StateBackend().authenticate(token=t) - self.assertEquals(user, self.user) + self.assertEqual(user, self.user) def test_authenticate_alt_character(self): t = Token(character_id=self.alt_character.character_id, character_owner_hash='2') user = StateBackend().authenticate(token=t) - self.assertEquals(user, self.user) + self.assertEqual(user, self.user) def test_authenticate_unclaimed_character(self): t = Token(character_id=self.unclaimed_character.character_id, character_name=self.unclaimed_character.character_name, character_owner_hash='3') diff --git a/allianceauth/authentication/tests/test_models.py b/allianceauth/authentication/tests/test_models.py index 485a3413..59469b26 100644 --- a/allianceauth/authentication/tests/test_models.py +++ b/allianceauth/authentication/tests/test_models.py @@ -36,8 +36,8 @@ class CharacterOwnershipTestCase(TestCase): character_owner_hash='1', ) co = CharacterOwnership.objects.get(character=self.character) - self.assertEquals(co.user, self.user) - self.assertEquals(co.owner_hash, '1') + self.assertEqual(co.user, self.user) + self.assertEqual(co.owner_hash, '1') def test_transfer_ownership(self): Token.objects.create( @@ -54,7 +54,7 @@ class CharacterOwnershipTestCase(TestCase): ) co = CharacterOwnership.objects.get(character=self.character) self.assertNotEqual(self.user, co.user) - self.assertEquals(self.alt_user, co.user) + self.assertEqual(self.alt_user, co.user) def test_clear_main_character(self): Token.objects.create( @@ -98,29 +98,29 @@ class StateTestCase(TestCase): def test_state_assignment_on_character_change(self): self.member_state.member_characters.add(self.test_character) self._refresh_user() - self.assertEquals(self.user.profile.state, self.member_state) + self.assertEqual(self.user.profile.state, self.member_state) self.member_state.member_characters.remove(self.test_character) self._refresh_user() - self.assertEquals(self.user.profile.state, self.guest_state) + self.assertEqual(self.user.profile.state, self.guest_state) def test_state_assignment_on_corporation_change(self): self.member_state.member_corporations.add(self.test_corporation) self._refresh_user() - self.assertEquals(self.user.profile.state, self.member_state) + self.assertEqual(self.user.profile.state, self.member_state) self.member_state.member_corporations.remove(self.test_corporation) self._refresh_user() - self.assertEquals(self.user.profile.state, self.guest_state) + self.assertEqual(self.user.profile.state, self.guest_state) def test_state_assignment_on_alliance_addition(self): self.member_state.member_alliances.add(self.test_alliance) self._refresh_user() - self.assertEquals(self.user.profile.state, self.member_state) + self.assertEqual(self.user.profile.state, self.member_state) self.member_state.member_alliances.remove(self.test_alliance) self._refresh_user() - self.assertEquals(self.user.profile.state, self.guest_state) + self.assertEqual(self.user.profile.state, self.guest_state) def test_state_assignment_on_higher_priority_state_creation(self): self.member_state.member_characters.add(self.test_character) @@ -130,10 +130,10 @@ class StateTestCase(TestCase): ) higher_state.member_characters.add(self.test_character) self._refresh_user() - self.assertEquals(higher_state, self.user.profile.state) + self.assertEqual(higher_state, self.user.profile.state) higher_state.member_characters.clear() self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) self.member_state.member_characters.clear() def test_state_assignment_on_lower_priority_state_creation(self): @@ -144,10 +144,10 @@ class StateTestCase(TestCase): ) lower_state.member_characters.add(self.test_character) self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) lower_state.member_characters.clear() self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) self.member_state.member_characters.clear() def test_state_assignment_on_priority_change(self): @@ -161,11 +161,11 @@ class StateTestCase(TestCase): lower_state.priority = 500 lower_state.save() self._refresh_user() - self.assertEquals(lower_state, self.user.profile.state) + self.assertEqual(lower_state, self.user.profile.state) lower_state.priority = 125 lower_state.save() self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) def test_state_assignment_on_state_deletion(self): self.member_state.member_characters.add(self.test_character) @@ -175,11 +175,11 @@ class StateTestCase(TestCase): ) higher_state.member_characters.add(self.test_character) self._refresh_user() - self.assertEquals(higher_state, self.user.profile.state) + self.assertEqual(higher_state, self.user.profile.state) higher_state.delete() self.assertFalse(State.objects.filter(name='Higher State').count()) self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) def test_state_assignment_on_public_toggle(self): self.member_state.member_characters.add(self.test_character) @@ -188,26 +188,26 @@ class StateTestCase(TestCase): priority=200, ) self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) higher_state.public = True higher_state.save() self._refresh_user() - self.assertEquals(higher_state, self.user.profile.state) + self.assertEqual(higher_state, self.user.profile.state) higher_state.public = False higher_state.save() self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) def test_state_assignment_on_active_changed(self): self.member_state.member_characters.add(self.test_character) self.user.is_active = False self.user.save() self._refresh_user() - self.assertEquals(self.user.profile.state, self.guest_state) + self.assertEqual(self.user.profile.state, self.guest_state) self.user.is_active = True self.user.save() self._refresh_user() - self.assertEquals(self.user.profile.state, self.member_state) + self.assertEqual(self.user.profile.state, self.member_state) class CharacterOwnershipCheckTestCase(TestCase): diff --git a/allianceauth/authentication/views.py b/allianceauth/authentication/views.py index b173ec9f..e4331b8c 100644 --- a/allianceauth/authentication/views.py +++ b/allianceauth/authentication/views.py @@ -63,7 +63,7 @@ def dashboard(request): @login_required @token_required(scopes=settings.LOGIN_TOKEN_SCOPES) def main_character_change(request, token): - logger.debug("main_character_change called by user %s for character %s" % (request.user, token.character_name)) + logger.debug(f"main_character_change called by user {request.user} for character {token.character_name}") try: co = CharacterOwnership.objects.get(character__character_id=token.character_id, user=request.user) except CharacterOwnership.DoesNotExist: @@ -154,7 +154,7 @@ class RegistrationView(BaseRegistrationView): if not getattr(settings, 'REGISTRATION_VERIFY_EMAIL', True): # Keep the request so the user can be automagically logged in. setattr(self, 'request', request) - return super(RegistrationView, self).dispatch(request, *args, **kwargs) + return super().dispatch(request, *args, **kwargs) def register(self, form): user = User.objects.get(pk=self.request.session.get('registration_uid')) @@ -173,7 +173,7 @@ class RegistrationView(BaseRegistrationView): return signing.dumps(obj=[getattr(user, User.USERNAME_FIELD), user.email], salt=REGISTRATION_SALT) def get_email_context(self, activation_key): - context = super(RegistrationView, self).get_email_context(activation_key) + context = super().get_email_context(activation_key) context['url'] = context['site'].domain + reverse('registration_activate', args=[activation_key]) return context diff --git a/allianceauth/bin/allianceauth.py b/allianceauth/bin/allianceauth.py index ae54e1fd..5d64601f 100644 --- a/allianceauth/bin/allianceauth.py +++ b/allianceauth/bin/allianceauth.py @@ -41,7 +41,7 @@ def create_project(parser, options, args): # Call the command with extra context call_command(StartProject(), *args, **command_options) - print("Success! %(project_name)s has been created." % {'project_name': args[0]}) # noqa + print(f"Success! {args[0]} has been created.") # noqa def update_settings(parser, options, args): @@ -69,10 +69,10 @@ def update_settings(parser, options, args): template_settings_path = os.path.join(template_path, 'project_name/settings/base.py') # overwrite the local project's base settings - with open(template_settings_path, 'r') as template, open(settings_path, 'w') as target: + with open(template_settings_path) as template, open(settings_path, 'w') as target: target.write(template.read()) - print("Successfully updated %(project_name)s settings." % {'project_name': project_name}) + print(f"Successfully updated {project_name} settings.") COMMANDS = { diff --git a/allianceauth/corputils/managers.py b/allianceauth/corputils/managers.py index 8607b613..87b2ffdd 100644 --- a/allianceauth/corputils/managers.py +++ b/allianceauth/corputils/managers.py @@ -29,7 +29,7 @@ class CorpStatsQuerySet(models.QuerySet): if user.has_perm('corputils.view_state_corpstats'): queries.append(models.Q(corp__in=user.profile.state.member_corporations.all())) queries.append(models.Q(corp__alliance__in=user.profile.state.member_alliances.all())) - logger.debug('%s queries for user %s visible corpstats.' % (len(queries), user)) + logger.debug(f'{len(queries)} queries for user {user} visible corpstats.') # filter based on queries query = queries.pop() for q in queries: diff --git a/allianceauth/corputils/migrations/0001_initial.py b/allianceauth/corputils/migrations/0001_initial.py index 7da61bdd..49d71b75 100644 --- a/allianceauth/corputils/migrations/0001_initial.py +++ b/allianceauth/corputils/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-12-14 21:36 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/corputils/migrations/0002_migrate_permissions.py b/allianceauth/corputils/migrations/0002_migrate_permissions.py index 2c0e462d..fce155e4 100644 --- a/allianceauth/corputils/migrations/0002_migrate_permissions.py +++ b/allianceauth/corputils/migrations/0002_migrate_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-12-14 21:48 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/corputils/migrations/0003_granular_permissions.py b/allianceauth/corputils/migrations/0003_granular_permissions.py index 8256106d..446a0c48 100644 --- a/allianceauth/corputils/migrations/0003_granular_permissions.py +++ b/allianceauth/corputils/migrations/0003_granular_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:35 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/corputils/migrations/0004_member_models.py b/allianceauth/corputils/migrations/0004_member_models.py index 83b6b546..b8e2e291 100644 --- a/allianceauth/corputils/migrations/0004_member_models.py +++ b/allianceauth/corputils/migrations/0004_member_models.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-26 20:13 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion @@ -48,7 +47,7 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='corpmember', - unique_together=set([('corpstats', 'character_id')]), + unique_together={('corpstats', 'character_id')}, ), migrations.RunPython(convert_json_to_members, convert_members_to_json), migrations.RemoveField( diff --git a/allianceauth/corputils/migrations/0005_cleanup_permissions.py b/allianceauth/corputils/migrations/0005_cleanup_permissions.py index 27f8d73f..f73c37ca 100644 --- a/allianceauth/corputils/migrations/0005_cleanup_permissions.py +++ b/allianceauth/corputils/migrations/0005_cleanup_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.2 on 2017-06-10 15:34 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/corputils/models.py b/allianceauth/corputils/models.py index 8d7c6628..7ac03b7e 100644 --- a/allianceauth/corputils/models.py +++ b/allianceauth/corputils/models.py @@ -43,7 +43,7 @@ class CorpStats(models.Model): objects = CorpStatsManager() def __str__(self): - return "%s for %s" % (self.__class__.__name__, self.corp) + return f"{self.__class__.__name__} for {self.corp}" def update(self): try: @@ -73,7 +73,7 @@ class CorpStats(models.Model): self.save() except TokenError as e: - logger.warning("%s failed to update: %s" % (self, e)) + logger.warning(f"{self} failed to update: {e}") if self.token.user: notify( self.token.user, "%s failed to update with your ESI token." % self, @@ -81,9 +81,9 @@ class CorpStats(models.Model): level="error") self.delete() except HTTPForbidden as e: - logger.warning("%s failed to update: %s" % (self, e)) + logger.warning(f"{self} failed to update: {e}") if self.token.user: - notify(self.token.user, "%s failed to update with your ESI token." % self, message="%s: %s" % (e.status_code, e.message), level="error") + notify(self.token.user, "%s failed to update with your ESI token." % self, message=f"{e.status_code}: {e.message}", level="error") self.delete() except AssertionError: logger.warning("%s token character no longer in corp." % self) @@ -99,7 +99,7 @@ class CorpStats(models.Model): @property def user_count(self): - return len(set([m.main_character for m in self.members.all() if m.main_character])) + return len({m.main_character for m in self.members.all() if m.main_character}) @property def registered_member_count(self): diff --git a/allianceauth/corputils/tests.py b/allianceauth/corputils/tests.py index a07e338f..43e1f720 100644 --- a/allianceauth/corputils/tests.py +++ b/allianceauth/corputils/tests.py @@ -243,7 +243,7 @@ class CorpMemberTestCase(TestCase): CharacterOwnership.objects.create(character=character, user=self.user, owner_hash='b') self.member.refresh_from_db() self.assertNotEqual(self.member.main_character, self.member.character) - self.assertEquals(self.member.main_character, self.user.profile.main_character) + self.assertEqual(self.member.main_character, self.user.profile.main_character) # test when is main old_main = self.user.profile.main_character @@ -274,7 +274,7 @@ class CorpMemberTestCase(TestCase): AuthUtils.connect_signals() def test_portrait_url(self): - self.assertEquals(self.member.portrait_url(size=32), 'https://images.evetech.net/characters/2/portrait?size=32') - self.assertEquals(self.member.portrait_url(size=32), self.member.portrait_url_32) - self.assertEquals(self.member.portrait_url(size=64), self.member.portrait_url_64) - self.assertEquals(self.member.portrait_url(size=128), self.member.portrait_url_128) + self.assertEqual(self.member.portrait_url(size=32), 'https://images.evetech.net/characters/2/portrait?size=32') + self.assertEqual(self.member.portrait_url(size=32), self.member.portrait_url_32) + self.assertEqual(self.member.portrait_url(size=64), self.member.portrait_url_64) + self.assertEqual(self.member.portrait_url(size=128), self.member.portrait_url_128) diff --git a/allianceauth/eveonline/admin.py b/allianceauth/eveonline/admin.py index 1333fa9d..cb3e5c93 100644 --- a/allianceauth/eveonline/admin.py +++ b/allianceauth/eveonline/admin.py @@ -10,14 +10,14 @@ from .models import EveCorporationInfo class EveEntityExistsError(forms.ValidationError): def __init__(self, entity_type_name, id): - super(EveEntityExistsError, self).__init__( - message='{} with ID {} already exists.'.format(entity_type_name, id)) + super().__init__( + message=f'{entity_type_name} with ID {id} already exists.') class EveEntityNotFoundError(forms.ValidationError): def __init__(self, entity_type_name, id): - super(EveEntityNotFoundError, self).__init__( - message='{} with ID {} not found.'.format(entity_type_name, id)) + super().__init__( + message=f'{entity_type_name} with ID {id} not found.') class EveEntityForm(forms.ModelForm): @@ -170,4 +170,4 @@ class EveCharacterAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): if not obj or not obj.pk: return EveCharacterForm - return super(EveCharacterAdmin, self).get_form(request, obj=obj, **kwargs) + return super().get_form(request, obj=obj, **kwargs) diff --git a/allianceauth/eveonline/autogroups/admin.py b/allianceauth/eveonline/autogroups/admin.py index 888be4ed..7f2ebabe 100644 --- a/allianceauth/eveonline/autogroups/admin.py +++ b/allianceauth/eveonline/autogroups/admin.py @@ -10,7 +10,7 @@ logger = logging.getLogger(__name__) def sync_user_groups(modeladmin, request, queryset): for agc in queryset: - logger.debug("update_all_states_group_membership for {}".format(agc)) + logger.debug(f"update_all_states_group_membership for {agc}") agc.update_all_states_group_membership() @@ -29,7 +29,7 @@ class AutogroupsConfigAdmin(admin.ModelAdmin): return [] def get_actions(self, request): - actions = super(AutogroupsConfigAdmin, self).get_actions(request) + actions = super().get_actions(request) actions['sync_user_groups'] = (sync_user_groups, 'sync_user_groups', 'Sync all users groups for this Autogroup Config') diff --git a/allianceauth/eveonline/autogroups/migrations/0001_initial.py b/allianceauth/eveonline/autogroups/migrations/0001_initial.py index 3c552693..33c1ab42 100644 --- a/allianceauth/eveonline/autogroups/migrations/0001_initial.py +++ b/allianceauth/eveonline/autogroups/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.6 on 2017-12-23 04:30 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/eveonline/autogroups/models.py b/allianceauth/eveonline/autogroups/models.py index 8cf6f319..88bc3ece 100644 --- a/allianceauth/eveonline/autogroups/models.py +++ b/allianceauth/eveonline/autogroups/models.py @@ -26,7 +26,7 @@ class AutogroupsConfigManager(models.Manager): for config in self.filter(states=state): logger.debug("in state loop") for user in users: - logger.debug("in user loop for {}".format(user)) + logger.debug(f"in user loop for {user}") config.update_group_membership_for_user(user) def update_groups_for_user(self, user: User, state: State = None): @@ -81,7 +81,7 @@ class AutogroupsConfig(models.Model): objects = AutogroupsConfigManager() def __init__(self, *args, **kwargs): - super(AutogroupsConfig, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def __repr__(self): return self.__class__.__name__ @@ -111,24 +111,24 @@ class AutogroupsConfig(models.Model): group = None try: if not self.alliance_groups or not self.user_entitled_to_groups(user): - logger.debug('User {} does not have required state for alliance group membership'.format(user)) + logger.debug(f'User {user} does not have required state for alliance group membership') return else: alliance = user.profile.main_character.alliance if alliance is None: - logger.debug('User {} alliance is None, cannot update group membership'.format(user)) + logger.debug(f'User {user} alliance is None, cannot update group membership') return group = self.get_alliance_group(alliance) except EveAllianceInfo.DoesNotExist: - logger.debug('User {} main characters alliance does not exist in the database. Creating.'.format(user)) + logger.debug(f'User {user} main characters alliance does not exist in the database. Creating.') alliance = EveAllianceInfo.objects.create_alliance(user.profile.main_character.alliance_id) group = self.get_alliance_group(alliance) except AttributeError: - logger.warning('User {} does not have a main character. Group membership not updated'.format(user)) + logger.warning(f'User {user} does not have a main character. Group membership not updated') finally: self.remove_user_from_alliance_groups(user, except_group=group) if group is not None: - logger.debug('Adding user {} to alliance group {}'.format(user, group)) + logger.debug(f'Adding user {user} to alliance group {group}') user.groups.add(group) @transaction.atomic @@ -136,20 +136,20 @@ class AutogroupsConfig(models.Model): group = None try: if not self.corp_groups or not self.user_entitled_to_groups(user): - logger.debug('User {} does not have required state for corp group membership'.format(user)) + logger.debug(f'User {user} does not have required state for corp group membership') else: corp = user.profile.main_character.corporation group = self.get_corp_group(corp) except EveCorporationInfo.DoesNotExist: - logger.debug('User {} main characters corporation does not exist in the database. Creating.'.format(user)) + logger.debug(f'User {user} main characters corporation does not exist in the database. Creating.') corp = EveCorporationInfo.objects.create_corporation(user.profile.main_character.corporation_id) group = self.get_corp_group(corp) except AttributeError: - logger.warning('User {} does not have a main character. Group membership not updated'.format(user)) + logger.warning(f'User {user} does not have a main character. Group membership not updated') finally: self.remove_user_from_corp_groups(user, except_group=group) if group is not None: - logger.debug('Adding user {} to corp group {}'.format(user, group)) + logger.debug(f'Adding user {user} to corp group {group}') user.groups.add(group) @transaction.atomic diff --git a/allianceauth/eveonline/autogroups/signals.py b/allianceauth/eveonline/autogroups/signals.py index 2ef7397b..c2b8c11a 100644 --- a/allianceauth/eveonline/autogroups/signals.py +++ b/allianceauth/eveonline/autogroups/signals.py @@ -15,7 +15,7 @@ def pre_save_config(sender, instance, *args, **kwargs): Checks if enable was toggled on group config and deletes groups if necessary. """ - logger.debug("Received pre_save from {}".format(instance)) + logger.debug(f"Received pre_save from {instance}") if not instance.pk: # new model being created return diff --git a/allianceauth/eveonline/autogroups/tests/__init__.py b/allianceauth/eveonline/autogroups/tests/__init__.py index 51704c12..cd1c4d68 100644 --- a/allianceauth/eveonline/autogroups/tests/__init__.py +++ b/allianceauth/eveonline/autogroups/tests/__init__.py @@ -9,7 +9,7 @@ MODULE_PATH = 'allianceauth.eveonline.autogroups' def patch(target, *args, **kwargs): - return mock.patch('{}{}'.format(MODULE_PATH, target), *args, **kwargs) + return mock.patch(f'{MODULE_PATH}{target}', *args, **kwargs) def connect_signals(): diff --git a/allianceauth/eveonline/evelinks/eveimageserver.py b/allianceauth/eveonline/evelinks/eveimageserver.py index d2f51c27..172c1bbc 100644 --- a/allianceauth/eveonline/evelinks/eveimageserver.py +++ b/allianceauth/eveonline/evelinks/eveimageserver.py @@ -56,15 +56,15 @@ def _eve_entity_image_url( tenants = ['tranquility', 'singularity'] if not entity_id: - raise ValueError('Invalid entity_id: {}'.format(entity_id)) + raise ValueError(f'Invalid entity_id: {entity_id}') else: entity_id = int(entity_id) if not size or size < 32 or size > 1024 or (size & (size - 1) != 0): - raise ValueError('Invalid size: {}'.format(size)) + raise ValueError(f'Invalid size: {size}') if category not in categories: - raise ValueError('Invalid category {}'.format(category)) + raise ValueError(f'Invalid category {category}') else: endpoint = categories[category]['endpoint'] @@ -78,7 +78,7 @@ def _eve_entity_image_url( variant = categories[category]['variants'][0] if tenant and tenant not in tenants: - raise ValueError('Invalid tenant {}'.format(tenant)) + raise ValueError(f'Invalid tenant {tenant}') # compose result URL result = '{}/{}/{}/{}?size={}'.format( @@ -89,7 +89,7 @@ def _eve_entity_image_url( size ) if tenant: - result += '&tenant={}'.format(tenant) + result += f'&tenant={tenant}' return result diff --git a/allianceauth/eveonline/evelinks/evewho.py b/allianceauth/eveonline/evelinks/evewho.py index 3062ba45..6fd05b14 100644 --- a/allianceauth/eveonline/evelinks/evewho.py +++ b/allianceauth/eveonline/evelinks/evewho.py @@ -31,7 +31,7 @@ def _build_url(category: str, eve_id: int) -> str: url = urljoin( _BASE_URL, - '{}/{}'.format(partial, int(eve_id)) + f'{partial}/{int(eve_id)}' ) return url diff --git a/allianceauth/eveonline/evelinks/zkillboard.py b/allianceauth/eveonline/evelinks/zkillboard.py index 0023d071..3bba9833 100644 --- a/allianceauth/eveonline/evelinks/zkillboard.py +++ b/allianceauth/eveonline/evelinks/zkillboard.py @@ -39,7 +39,7 @@ def _build_url(category: str, eve_id: int) -> str: url = urljoin( _BASE_URL, - '{}/{}/'.format(partial, int(eve_id)) + f'{partial}/{int(eve_id)}/' ) return url diff --git a/allianceauth/eveonline/migrations/0001_initial.py b/allianceauth/eveonline/migrations/0001_initial.py index e2c2589d..a647ca0b 100644 --- a/allianceauth/eveonline/migrations/0001_initial.py +++ b/allianceauth/eveonline/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:39 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/eveonline/migrations/0002_remove_eveapikeypair_error_count.py b/allianceauth/eveonline/migrations/0002_remove_eveapikeypair_error_count.py index 5c7de29e..641a7334 100644 --- a/allianceauth/eveonline/migrations/0002_remove_eveapikeypair_error_count.py +++ b/allianceauth/eveonline/migrations/0002_remove_eveapikeypair_error_count.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-10 20:20 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/eveonline/migrations/0003_auto_20161026_0149.py b/allianceauth/eveonline/migrations/0003_auto_20161026_0149.py index 6ec80863..0dda48fa 100644 --- a/allianceauth/eveonline/migrations/0003_auto_20161026_0149.py +++ b/allianceauth/eveonline/migrations/0003_auto_20161026_0149.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-10-26 01:49 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/eveonline/migrations/0004_eveapikeypair_sso_verified.py b/allianceauth/eveonline/migrations/0004_eveapikeypair_sso_verified.py index 140aff15..0dd4f83a 100644 --- a/allianceauth/eveonline/migrations/0004_eveapikeypair_sso_verified.py +++ b/allianceauth/eveonline/migrations/0004_eveapikeypair_sso_verified.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-11-01 04:20 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/eveonline/migrations/0005_remove_eveallianceinfo_member_count.py b/allianceauth/eveonline/migrations/0005_remove_eveallianceinfo_member_count.py index 604146f2..ad663e30 100644 --- a/allianceauth/eveonline/migrations/0005_remove_eveallianceinfo_member_count.py +++ b/allianceauth/eveonline/migrations/0005_remove_eveallianceinfo_member_count.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-12-16 23:22 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/eveonline/migrations/0006_allow_null_evecharacter_alliance.py b/allianceauth/eveonline/migrations/0006_allow_null_evecharacter_alliance.py index f78a2d3c..d0c3c664 100644 --- a/allianceauth/eveonline/migrations/0006_allow_null_evecharacter_alliance.py +++ b/allianceauth/eveonline/migrations/0006_allow_null_evecharacter_alliance.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2017-01-02 19:23 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/eveonline/migrations/0007_unique_id_name.py b/allianceauth/eveonline/migrations/0007_unique_id_name.py index f91733c8..1adf7463 100644 --- a/allianceauth/eveonline/migrations/0007_unique_id_name.py +++ b/allianceauth/eveonline/migrations/0007_unique_id_name.py @@ -1,11 +1,10 @@ # Generated by Django 1.10.5 on 2017-01-18 13:20 -from __future__ import unicode_literals from django.db import migrations, models def get_duplicates(items): - return set([item for item in items if items.count(item) > 1]) + return {item for item in items if items.count(item) > 1} def enforce_unique_characters(apps, schema_editor): diff --git a/allianceauth/eveonline/migrations/0008_remove_apikeys.py b/allianceauth/eveonline/migrations/0008_remove_apikeys.py index e8475693..f81126c5 100644 --- a/allianceauth/eveonline/migrations/0008_remove_apikeys.py +++ b/allianceauth/eveonline/migrations/0008_remove_apikeys.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:09 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/eveonline/migrations/0009_on_delete.py b/allianceauth/eveonline/migrations/0009_on_delete.py index 9cfa03e2..d47b068b 100644 --- a/allianceauth/eveonline/migrations/0009_on_delete.py +++ b/allianceauth/eveonline/migrations/0009_on_delete.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/eveonline/providers.py b/allianceauth/eveonline/providers.py index 1373c49d..5ccff694 100644 --- a/allianceauth/eveonline/providers.py +++ b/allianceauth/eveonline/providers.py @@ -34,10 +34,10 @@ class ObjectNotFound(Exception): self.type = type_name def __str__(self): - return '%s with ID %s not found.' % (self.type, self.id) + return f'{self.type} with ID {self.id} not found.' -class Entity(object): +class Entity: def __init__(self, id=None, name=None): self.id = id self.name = name @@ -46,7 +46,7 @@ class Entity(object): return self.name def __repr__(self): - return "<{} ({}): {}>".format(self.__class__.__name__, self.id, self.name) + return f"<{self.__class__.__name__} ({self.id}): {self.name}>" def __bool__(self): return bool(self.id) @@ -57,7 +57,7 @@ class Entity(object): class Corporation(Entity): def __init__(self, ticker=None, ceo_id=None, members=None, alliance_id=None, **kwargs): - super(Corporation, self).__init__(**kwargs) + super().__init__(**kwargs) self.ticker = ticker self.ceo_id = ceo_id self.members = members @@ -82,7 +82,7 @@ class Corporation(Entity): class Alliance(Entity): def __init__(self, ticker=None, corp_ids=None, executor_corp_id=None, **kwargs): - super(Alliance, self).__init__(**kwargs) + super().__init__(**kwargs) self.ticker = ticker self.corp_ids = corp_ids self.executor_corp_id = executor_corp_id @@ -97,7 +97,7 @@ class Alliance(Entity): @property def corps(self): - return sorted([self.corp(c_id) for c_id in self.corp_ids], key=lambda x: x.name) + return sorted((self.corp(c_id) for c_id in self.corp_ids), key=lambda x: x.name) @property def executor_corp(self): @@ -108,7 +108,7 @@ class Alliance(Entity): class Character(Entity): def __init__(self, corp_id=None, alliance_id=None, **kwargs): - super(Character, self).__init__(**kwargs) + super().__init__(**kwargs) self.corp_id = corp_id self.alliance_id = alliance_id self._corp = None @@ -129,10 +129,10 @@ class Character(Entity): class ItemType(Entity): def __init__(self, **kwargs): - super(ItemType, self).__init__(**kwargs) + super().__init__(**kwargs) -class EveProvider(object): +class EveProvider: def get_alliance(self, alliance_id): """ :return: an Alliance object for the given ID diff --git a/allianceauth/eveonline/tests/__init__.py b/allianceauth/eveonline/tests/__init__.py index 798d32d1..c2b82426 100644 --- a/allianceauth/eveonline/tests/__init__.py +++ b/allianceauth/eveonline/tests/__init__.py @@ -18,7 +18,7 @@ def set_logger(logger_name: str, name: str) -> object: '%(asctime)s - %(levelname)s - %(module)s:%(funcName)s - %(message)s' ) f_handler = logging.FileHandler( - '{}.log'.format(os.path.splitext(name)[0]), + f'{os.path.splitext(name)[0]}.log', 'w+' ) f_handler.setFormatter(f_format) diff --git a/allianceauth/fleetactivitytracking/admin.py b/allianceauth/fleetactivitytracking/admin.py index 8fb2cf70..6ac8ca30 100644 --- a/allianceauth/fleetactivitytracking/admin.py +++ b/allianceauth/fleetactivitytracking/admin.py @@ -1,4 +1,3 @@ - from django.contrib import admin from allianceauth.fleetactivitytracking.models import Fatlink, Fat diff --git a/allianceauth/fleetactivitytracking/apps.py b/allianceauth/fleetactivitytracking/apps.py index 86c4fe11..89357491 100644 --- a/allianceauth/fleetactivitytracking/apps.py +++ b/allianceauth/fleetactivitytracking/apps.py @@ -1,4 +1,3 @@ - from django.apps import AppConfig diff --git a/allianceauth/fleetactivitytracking/forms.py b/allianceauth/fleetactivitytracking/forms.py index 1c00430d..7ef820c2 100644 --- a/allianceauth/fleetactivitytracking/forms.py +++ b/allianceauth/fleetactivitytracking/forms.py @@ -1,4 +1,3 @@ - from django import forms from django.utils.translation import ugettext_lazy as _ diff --git a/allianceauth/fleetactivitytracking/migrations/0001_initial.py b/allianceauth/fleetactivitytracking/migrations/0001_initial.py index a74865d0..64196a11 100644 --- a/allianceauth/fleetactivitytracking/migrations/0001_initial.py +++ b/allianceauth/fleetactivitytracking/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:39 -from __future__ import unicode_literals import django.db.models.deletion from django.conf import settings @@ -54,6 +53,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='fat', - unique_together=set([('character', 'fatlink')]), + unique_together={('character', 'fatlink')}, ), ] diff --git a/allianceauth/fleetactivitytracking/migrations/0002_auto_20160905_2220.py b/allianceauth/fleetactivitytracking/migrations/0002_auto_20160905_2220.py index 19085a8f..563b1e90 100644 --- a/allianceauth/fleetactivitytracking/migrations/0002_auto_20160905_2220.py +++ b/allianceauth/fleetactivitytracking/migrations/0002_auto_20160905_2220.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 22:20 -from __future__ import unicode_literals import datetime from django.db import migrations, models diff --git a/allianceauth/fleetactivitytracking/migrations/0003_auto_20160906_2354.py b/allianceauth/fleetactivitytracking/migrations/0003_auto_20160906_2354.py index 2f31273d..435f0a9a 100644 --- a/allianceauth/fleetactivitytracking/migrations/0003_auto_20160906_2354.py +++ b/allianceauth/fleetactivitytracking/migrations/0003_auto_20160906_2354.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-06 23:54 -from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone diff --git a/allianceauth/fleetactivitytracking/migrations/0004_make_strings_more_stringy.py b/allianceauth/fleetactivitytracking/migrations/0004_make_strings_more_stringy.py index 8dc13316..f226a4c2 100644 --- a/allianceauth/fleetactivitytracking/migrations/0004_make_strings_more_stringy.py +++ b/allianceauth/fleetactivitytracking/migrations/0004_make_strings_more_stringy.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:35 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/fleetactivitytracking/views.py b/allianceauth/fleetactivitytracking/views.py index 7e97f45b..246842e8 100644 --- a/allianceauth/fleetactivitytracking/views.py +++ b/allianceauth/fleetactivitytracking/views.py @@ -36,7 +36,7 @@ get_universe_structures_structure_id logger = logging.getLogger(__name__) -class CorpStat(object): +class CorpStat: def __init__(self, corp_id, start_of_month, start_of_next_month, corp=None): if corp: self.corp = corp @@ -53,7 +53,7 @@ class CorpStat(object): return "%.2f" % 0 -class MemberStat(object): +class MemberStat: def __init__(self, member, start_of_month, start_of_next_month, mainchid=None): if mainchid: self.mainchid = mainchid @@ -215,7 +215,7 @@ def fatlink_monthly_personal_statistics_view(request, year, month, char_id=None) user = EveCharacter.objects.get(character_id=char_id).user else: user = request.user - logger.debug("Personal monthly statistics view for user %s called by %s" % (user, request.user)) + logger.debug(f"Personal monthly statistics view for user {user} called by {request.user}") personal_fats = Fat.objects.filter(user=user)\ .filter(fatlink__fatdatetime__gte=start_of_month).filter(fatlink__fatdatetime__lt=start_of_next_month) @@ -347,7 +347,7 @@ def modify_fatlink_view(request, fat_hash=None): if request.GET.get('removechar', None): character_id = request.GET.get('removechar') character = EveCharacter.objects.get(character_id=character_id) - logger.debug("Removing character %s from fleetactivitytracking %s" % (character.character_name, fatlink)) + logger.debug(f"Removing character {character.character_name} from fleetactivitytracking {fatlink}") Fat.objects.filter(fatlink=fatlink).filter(character=character).delete() diff --git a/allianceauth/groupmanagement/migrations/0001_initial.py b/allianceauth/groupmanagement/migrations/0001_initial.py index f3c6dfe1..c6112559 100644 --- a/allianceauth/groupmanagement/migrations/0001_initial.py +++ b/allianceauth/groupmanagement/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:39 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/groupmanagement/migrations/0002_auto_20160906_2354.py b/allianceauth/groupmanagement/migrations/0002_auto_20160906_2354.py index 79ff2c0f..76cef366 100644 --- a/allianceauth/groupmanagement/migrations/0002_auto_20160906_2354.py +++ b/allianceauth/groupmanagement/migrations/0002_auto_20160906_2354.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-06 23:54 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/groupmanagement/migrations/0003_default_groups.py b/allianceauth/groupmanagement/migrations/0003_default_groups.py index 2c28e2fa..afe1bed0 100644 --- a/allianceauth/groupmanagement/migrations/0003_default_groups.py +++ b/allianceauth/groupmanagement/migrations/0003_default_groups.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-09 23:22 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings diff --git a/allianceauth/groupmanagement/migrations/0004_authgroup.py b/allianceauth/groupmanagement/migrations/0004_authgroup.py index 709b2ac5..b0540b05 100644 --- a/allianceauth/groupmanagement/migrations/0004_authgroup.py +++ b/allianceauth/groupmanagement/migrations/0004_authgroup.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-04 10:25 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/groupmanagement/migrations/0005_authgroup_public.py b/allianceauth/groupmanagement/migrations/0005_authgroup_public.py index 924edaac..ec5a6324 100644 --- a/allianceauth/groupmanagement/migrations/0005_authgroup_public.py +++ b/allianceauth/groupmanagement/migrations/0005_authgroup_public.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-04 06:11 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/groupmanagement/migrations/0006_request_groups_perm.py b/allianceauth/groupmanagement/migrations/0006_request_groups_perm.py index e1501bcd..69544c9c 100644 --- a/allianceauth/groupmanagement/migrations/0006_request_groups_perm.py +++ b/allianceauth/groupmanagement/migrations/0006_request_groups_perm.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-04 07:17 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings diff --git a/allianceauth/groupmanagement/migrations/0007_on_delete.py b/allianceauth/groupmanagement/migrations/0007_on_delete.py index ba038502..9193a820 100644 --- a/allianceauth/groupmanagement/migrations/0007_on_delete.py +++ b/allianceauth/groupmanagement/migrations/0007_on_delete.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 -from __future__ import unicode_literals import django.contrib.auth.models from django.db import migrations diff --git a/allianceauth/groupmanagement/migrations/0008_remove_authgroup_permissions.py b/allianceauth/groupmanagement/migrations/0008_remove_authgroup_permissions.py index 7aca9f2b..8e6fa137 100644 --- a/allianceauth/groupmanagement/migrations/0008_remove_authgroup_permissions.py +++ b/allianceauth/groupmanagement/migrations/0008_remove_authgroup_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.10 on 2018-02-23 23:09 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/groupmanagement/models.py b/allianceauth/groupmanagement/models.py index e957204d..5fb60a75 100644 --- a/allianceauth/groupmanagement/models.py +++ b/allianceauth/groupmanagement/models.py @@ -113,7 +113,7 @@ class AuthGroup(models.Model): class Meta: permissions = ( - ("request_groups", u"Can request non-public groups"), + ("request_groups", "Can request non-public groups"), ) default_permissions = tuple() diff --git a/allianceauth/groupmanagement/signals.py b/allianceauth/groupmanagement/signals.py index 0392f4a9..99af3d5d 100644 --- a/allianceauth/groupmanagement/signals.py +++ b/allianceauth/groupmanagement/signals.py @@ -9,7 +9,7 @@ logger = logging.getLogger(__name__) @receiver(state_changed) def check_groups_on_state_change(sender, user, state, **kwargs): logger.debug( - "Checking group memberships for %s based on new state %s" % (user, state) + f"Checking group memberships for {user} based on new state {state}" ) state_groups = ( user.groups.select_related("authgroup").exclude(authgroup__states=None) @@ -17,6 +17,6 @@ def check_groups_on_state_change(sender, user, state, **kwargs): for group in state_groups: if not group.authgroup.states.filter(id=state.id).exists(): logger.info( - "Removing user %s from group %s due to missing state" % (user, group) + f"Removing user {user} from group {group} due to missing state" ) user.groups.remove(group) diff --git a/allianceauth/groupmanagement/tests/test_admin.py b/allianceauth/groupmanagement/tests/test_admin.py index 364309d9..5b32ba10 100644 --- a/allianceauth/groupmanagement/tests/test_admin.py +++ b/allianceauth/groupmanagement/tests/test_admin.py @@ -25,7 +25,7 @@ else: MODULE_PATH = 'allianceauth.groupmanagement.admin' -class MockRequest(object): +class MockRequest: def __init__(self, user=None): self.user = user diff --git a/allianceauth/groupmanagement/views.py b/allianceauth/groupmanagement/views.py index 2e12f2f0..bae689f3 100755 --- a/allianceauth/groupmanagement/views.py +++ b/allianceauth/groupmanagement/views.py @@ -42,7 +42,7 @@ def group_management(request): else: acceptrequests.append(grouprequest) - logger.debug("Providing user %s with %s acceptrequests and %s leaverequests." % ( + logger.debug("Providing user {} with {} acceptrequests and {} leaverequests.".format( request.user, len(acceptrequests), len(leaverequests))) render_items = {'acceptrequests': acceptrequests, 'leaverequests': leaverequests} @@ -78,7 +78,7 @@ def group_membership_audit(request, group_id): # Check its a joinable group i.e. not corp or internal # And the user has permission to manage it if not GroupManager.check_internal_group(group) or not GroupManager.can_manage_group(request.user, group): - logger.warning("User %s attempted to view the membership of group %s but permission was denied" % (request.user, group_id)) + logger.warning(f"User {request.user} attempted to view the membership of group {group_id} but permission was denied") raise PermissionDenied except ObjectDoesNotExist: @@ -139,13 +139,13 @@ def group_membership_list(request, group_id): @login_required @user_passes_test(GroupManager.can_manage_groups) def group_membership_remove(request, group_id, user_id): - logger.debug("group_membership_remove called by user %s for group id %s on user id %s" % (request.user, group_id, user_id)) + logger.debug(f"group_membership_remove called by user {request.user} for group id {group_id} on user id {user_id}") group = get_object_or_404(Group, id=group_id) try: # Check its a joinable group i.e. not corp or internal # And the user has permission to manage it if not GroupManager.check_internal_group(group) or not GroupManager.can_manage_group(request.user, group): - logger.warning("User %s attempted to remove a user from group %s but permission was denied" % (request.user, group_id)) + logger.warning(f"User {request.user} attempted to remove a user from group {group_id} but permission was denied") raise PermissionDenied try: @@ -155,7 +155,7 @@ def group_membership_remove(request, group_id, user_id): log.save() # Remove group from user user.groups.remove(group) - logger.info("User %s removed user %s from group %s" % (request.user, user, group)) + logger.info(f"User {request.user} removed user {user} from group {group}") messages.success(request, _("Removed user %(user)s from group %(group)s.") % {"user": user, "group": group}) except ObjectDoesNotExist: messages.warning(request, _("User does not exist in that group")) @@ -169,7 +169,7 @@ def group_membership_remove(request, group_id, user_id): @login_required @user_passes_test(GroupManager.can_manage_groups) def group_accept_request(request, group_request_id): - logger.debug("group_accept_request called by user %s for grouprequest id %s" % (request.user, group_request_id)) + logger.debug(f"group_accept_request called by user {request.user} for grouprequest id {group_request_id}") group_request = get_object_or_404(GroupRequest, id=group_request_id) try: group, created = Group.objects.get_or_create(name=group_request.group.name) @@ -183,7 +183,7 @@ def group_accept_request(request, group_request_id): log = RequestLog(request_type=group_request.leave_request,group=group,request_info=group_request.__str__(),action=1,request_actor=request.user) log.save() group_request.delete() - logger.info("User %s accepted group request from user %s to group %s" % ( + logger.info("User {} accepted group request from user {} to group {}".format( request.user, group_request.user, group_request.group.name)) notify(group_request.user, "Group Application Accepted", level="success", message="Your application to %s has been accepted." % group_request.group) @@ -191,11 +191,11 @@ def group_accept_request(request, group_request_id): _('Accepted application from %(mainchar)s to %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) except PermissionDenied as p: - logger.warning("User %s attempted to accept group join request %s but permission was denied" % (request.user, group_request_id)) + logger.warning(f"User {request.user} attempted to accept group join request {group_request_id} but permission was denied") raise p except: messages.error(request, _('An unhandled error occurred while processing the application from %(mainchar)s to %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) - logger.exception("Unhandled exception occurred while user %s attempting to accept grouprequest id %s." % ( + logger.exception("Unhandled exception occurred while user {} attempting to accept grouprequest id {}.".format( request.user, group_request_id)) pass @@ -205,14 +205,14 @@ def group_accept_request(request, group_request_id): @login_required @user_passes_test(GroupManager.can_manage_groups) def group_reject_request(request, group_request_id): - logger.debug("group_reject_request called by user %s for group request id %s" % (request.user, group_request_id)) + logger.debug(f"group_reject_request called by user {request.user} for group request id {group_request_id}") group_request = get_object_or_404(GroupRequest, id=group_request_id) try: if not GroupManager.can_manage_group(request.user, group_request.group): raise PermissionDenied if group_request: - logger.info("User %s rejected group request from user %s to group %s" % ( + logger.info("User {} rejected group request from user {} to group {}".format( request.user, group_request.user, group_request.group.name)) log = RequestLog(request_type=group_request.leave_request,group=group_request.group,request_info=group_request.__str__(),action=0,request_actor=request.user) log.save() @@ -222,11 +222,11 @@ def group_reject_request(request, group_request_id): _('Rejected application from %(mainchar)s to %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) except PermissionDenied as p: - logger.warning("User %s attempted to reject group join request %s but permission was denied" % (request.user, group_request_id)) + logger.warning(f"User {request.user} attempted to reject group join request {group_request_id} but permission was denied") raise p except: messages.error(request, _('An unhandled error occurred while processing the application from %(mainchar)s to %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) - logger.exception("Unhandled exception occurred while user %s attempting to reject group request id %s" % ( + logger.exception("Unhandled exception occurred while user {} attempting to reject group request id {}".format( request.user, group_request_id)) pass @@ -237,7 +237,7 @@ def group_reject_request(request, group_request_id): @user_passes_test(GroupManager.can_manage_groups) def group_leave_accept_request(request, group_request_id): logger.debug( - "group_leave_accept_request called by user %s for group request id %s" % (request.user, group_request_id)) + f"group_leave_accept_request called by user {request.user} for group request id {group_request_id}") group_request = get_object_or_404(GroupRequest, id=group_request_id) try: if not GroupManager.can_manage_group(request.user, group_request.group): @@ -249,19 +249,19 @@ def group_leave_accept_request(request, group_request_id): log = RequestLog(request_type=group_request.leave_request,group=group_request.group,request_info=group_request.__str__(),action=1,request_actor=request.user) log.save() group_request.delete() - logger.info("User %s accepted group leave request from user %s to group %s" % ( + logger.info("User {} accepted group leave request from user {} to group {}".format( request.user, group_request.user, group_request.group.name)) notify(group_request.user, "Group Leave Request Accepted", level="success", message="Your request to leave %s has been accepted." % group_request.group) messages.success(request, _('Accepted application from %(mainchar)s to leave %(group)s.') % {"mainchar": group_request.main_char, "group": group_request.group}) except PermissionDenied as p: - logger.warning("User %s attempted to accept group leave request %s but permission was denied" % (request.user, group_request_id)) + logger.warning(f"User {request.user} attempted to accept group leave request {group_request_id} but permission was denied") raise p except: messages.error(request, _('An unhandled error occurred while processing the application from %(mainchar)s to leave %(group)s.') % { "mainchar": group_request.main_char, "group": group_request.group}) - logger.exception("Unhandled exception occurred while user %s attempting to accept group leave request id %s" % ( + logger.exception("Unhandled exception occurred while user {} attempting to accept group leave request id {}".format( request.user, group_request_id)) pass @@ -272,7 +272,7 @@ def group_leave_accept_request(request, group_request_id): @user_passes_test(GroupManager.can_manage_groups) def group_leave_reject_request(request, group_request_id): logger.debug( - "group_leave_reject_request called by user %s for group request id %s" % (request.user, group_request_id)) + f"group_leave_reject_request called by user {request.user} for group request id {group_request_id}") group_request = get_object_or_404(GroupRequest, id=group_request_id) try: if not GroupManager.can_manage_group(request.user, group_request.group): @@ -282,18 +282,18 @@ def group_leave_reject_request(request, group_request_id): log = RequestLog(request_type=group_request.leave_request,group=group_request.group,request_info=group_request.__str__(),action=0,request_actor=request.user) log.save() group_request.delete() - logger.info("User %s rejected group leave request from user %s for group %s" % ( + logger.info("User {} rejected group leave request from user {} for group {}".format( request.user, group_request.user, group_request.group.name)) notify(group_request.user, "Group Leave Request Rejected", level="danger", message="Your request to leave %s has been rejected." % group_request.group) messages.success(request, _('Rejected application from %(mainchar)s to leave %(group)s.') % { "mainchar": group_request.main_char, "group": group_request.group}) except PermissionDenied as p: - logger.warning("User %s attempted to reject group leave request %s but permission was denied" % (request.user, group_request_id)) + logger.warning(f"User {request.user} attempted to reject group leave request {group_request_id} but permission was denied") raise p except: messages.error(request, _('An unhandled error occurred while processing the application from %(mainchar)s to leave %(group)s.') % { "mainchar": group_request.main_char, "group": group_request.group}) - logger.exception("Unhandled exception occurred while user %s attempting to reject group leave request id %s" % ( + logger.exception("Unhandled exception occurred while user {} attempting to reject group leave request id {}".format( request.user, group_request_id)) pass @@ -324,25 +324,25 @@ def groups_view(request): @login_required def group_request_add(request, group_id): - logger.debug("group_request_add called by user %s for group id %s" % (request.user, group_id)) + logger.debug(f"group_request_add called by user {request.user} for group id {group_id}") group = Group.objects.get(id=group_id) state = request.user.profile.state if not GroupManager.joinable_group(group, state): - logger.warning("User %s attempted to join group id %s but it is not a joinable group" % (request.user, group_id)) + logger.warning(f"User {request.user} attempted to join group id {group_id} but it is not a joinable group") messages.warning(request, _("You cannot join that group")) return redirect('groupmanagement:groups') if group in request.user.groups.all(): # User is already a member of this group. - logger.warning("User %s attempted to join group id %s but they are already a member." % (request.user, group_id)) + logger.warning(f"User {request.user} attempted to join group id {group_id} but they are already a member.") messages.warning(request, _("You are already a member of that group.")) return redirect('groupmanagement:groups') if not request.user.has_perm('groupmanagement.request_groups') and not group.authgroup.public: # Does not have the required permission, trying to join a non-public group - logger.warning("User %s attempted to join group id %s but it is not a public group" % (request.user, group_id)) + logger.warning(f"User {request.user} attempted to join group id {group_id} but it is not a public group") messages.warning(request, _("You cannot join that group")) return redirect('groupmanagement:groups') if group.authgroup.open: - logger.info("%s joining %s as is an open group" % (request.user, group)) + logger.info(f"{request.user} joining {group} as is an open group") request.user.groups.add(group) request_info = request.user.username + ":" + group.name log = RequestLog(request_type=False, group=group, request_info=request_info, action=1, request_actor=request.user) @@ -350,7 +350,7 @@ def group_request_add(request, group_id): return redirect("groupmanagement:groups") req = GroupRequest.objects.filter(user=request.user, group=group) if len(req) > 0: - logger.info("%s attempted to join %s but already has an open application" % (request.user, group)) + logger.info(f"{request.user} attempted to join {group} but already has an open application") messages.warning(request, _("You already have a pending application for that group.")) return redirect("groupmanagement:groups") grouprequest = GroupRequest() @@ -359,25 +359,25 @@ def group_request_add(request, group_id): grouprequest.user = request.user grouprequest.leave_request = False grouprequest.save() - logger.info("Created group request for user %s to group %s" % (request.user, Group.objects.get(id=group_id))) + logger.info(f"Created group request for user {request.user} to group {Group.objects.get(id=group_id)}") messages.success(request, _('Applied to group %(group)s.') % {"group": group}) return redirect("groupmanagement:groups") @login_required def group_request_leave(request, group_id): - logger.debug("group_request_leave called by user %s for group id %s" % (request.user, group_id)) + logger.debug(f"group_request_leave called by user {request.user} for group id {group_id}") group = Group.objects.get(id=group_id) if not GroupManager.check_internal_group(group): - logger.warning("User %s attempted to leave group id %s but it is not a joinable group" % (request.user, group_id)) + logger.warning(f"User {request.user} attempted to leave group id {group_id} but it is not a joinable group") messages.warning(request, _("You cannot leave that group")) return redirect('groupmanagement:groups') if group not in request.user.groups.all(): - logger.debug("User %s attempted to leave group id %s but they are not a member" % (request.user, group_id)) + logger.debug(f"User {request.user} attempted to leave group id {group_id} but they are not a member") messages.warning(request, _("You are not a member of that group")) return redirect('groupmanagement:groups') if group.authgroup.open: - logger.info("%s leaving %s as is an open group" % (request.user, group)) + logger.info(f"{request.user} leaving {group} as is an open group") request_info = request.user.username + ":" + group.name log = RequestLog(request_type=True, group=group, request_info=request_info, action=1, request_actor=request.user) log.save() @@ -385,11 +385,11 @@ def group_request_leave(request, group_id): return redirect("groupmanagement:groups") req = GroupRequest.objects.filter(user=request.user, group=group) if len(req) > 0: - logger.info("%s attempted to leave %s but already has an pending leave request." % (request.user, group)) + logger.info(f"{request.user} attempted to leave {group} but already has an pending leave request.") messages.warning(request, _("You already have a pending leave request for that group.")) return redirect("groupmanagement:groups") if getattr(settings, 'AUTO_LEAVE', False): - logger.info("%s leaving joinable group %s due to auto_leave" % (request.user, group)) + logger.info(f"{request.user} leaving joinable group {group} due to auto_leave") request_info = request.user.username + ":" + group.name log = RequestLog(request_type=True, group=group, request_info=request_info, action=1, request_actor=request.user) log.save() @@ -401,6 +401,6 @@ def group_request_leave(request, group_id): grouprequest.user = request.user grouprequest.leave_request = True grouprequest.save() - logger.info("Created group leave request for user %s to group %s" % (request.user, Group.objects.get(id=group_id))) + logger.info(f"Created group leave request for user {request.user} to group {Group.objects.get(id=group_id)}") messages.success(request, _('Applied to leave group %(group)s.') % {"group": group}) return redirect("groupmanagement:groups") diff --git a/allianceauth/hooks.py b/allianceauth/hooks.py index b80f94d7..773daa12 100644 --- a/allianceauth/hooks.py +++ b/allianceauth/hooks.py @@ -67,7 +67,7 @@ def register(name, fn=None): logger.debug("Creating new hook %s" % name) _hooks[name] = [] - logger.debug('Registering hook %s for function %s' % (name, fn)) + logger.debug(f'Registering hook {name} for function {fn}') _hooks[name].append(func) if fn is None: @@ -98,7 +98,7 @@ def get_app_submodules(module_name): """ for name, module in get_app_modules(): if module_has_submodule(module, module_name): - yield name, import_module('{0}.{1}'.format(name, module_name)) + yield name, import_module(f'{name}.{module_name}') def register_all_hooks(): diff --git a/allianceauth/hrapplications/migrations/0001_initial.py b/allianceauth/hrapplications/migrations/0001_initial.py index f8d82d85..466e8b18 100644 --- a/allianceauth/hrapplications/migrations/0001_initial.py +++ b/allianceauth/hrapplications/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:39 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models @@ -117,10 +116,10 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='applicationresponse', - unique_together=set([('question', 'application')]), + unique_together={('question', 'application')}, ), migrations.AlterUniqueTogether( name='application', - unique_together=set([('form', 'user')]), + unique_together={('form', 'user')}, ), ] diff --git a/allianceauth/hrapplications/migrations/0002_choices_for_questions.py b/allianceauth/hrapplications/migrations/0002_choices_for_questions.py index bae97a65..4687a7d6 100644 --- a/allianceauth/hrapplications/migrations/0002_choices_for_questions.py +++ b/allianceauth/hrapplications/migrations/0002_choices_for_questions.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.4 on 2017-08-23 19:46 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/hrapplications/migrations/0003_applicationquestion_multi_select.py b/allianceauth/hrapplications/migrations/0003_applicationquestion_multi_select.py index a22c30a0..e9d7cc55 100644 --- a/allianceauth/hrapplications/migrations/0003_applicationquestion_multi_select.py +++ b/allianceauth/hrapplications/migrations/0003_applicationquestion_multi_select.py @@ -1,5 +1,4 @@ # Generated by Django 1.10 on 2017-10-20 13:51 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/hrapplications/migrations/0004_make_strings_more_stringy.py b/allianceauth/hrapplications/migrations/0004_make_strings_more_stringy.py index d4f15abd..4c0047ac 100644 --- a/allianceauth/hrapplications/migrations/0004_make_strings_more_stringy.py +++ b/allianceauth/hrapplications/migrations/0004_make_strings_more_stringy.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:35 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/hrapplications/migrations/0005_sorted_questions.py b/allianceauth/hrapplications/migrations/0005_sorted_questions.py index 52fbd815..7e32e458 100644 --- a/allianceauth/hrapplications/migrations/0005_sorted_questions.py +++ b/allianceauth/hrapplications/migrations/0005_sorted_questions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-27 03:29 -from __future__ import unicode_literals from django.db import migrations import sortedm2m.fields diff --git a/allianceauth/hrapplications/migrations/0006_remove_legacy_models.py b/allianceauth/hrapplications/migrations/0006_remove_legacy_models.py index a27b4e2a..62c583c6 100644 --- a/allianceauth/hrapplications/migrations/0006_remove_legacy_models.py +++ b/allianceauth/hrapplications/migrations/0006_remove_legacy_models.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.2 on 2017-06-08 02:54 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/hrapplications/views.py b/allianceauth/hrapplications/views.py index db0713d4..e4aecd41 100755 --- a/allianceauth/hrapplications/views.py +++ b/allianceauth/hrapplications/views.py @@ -38,7 +38,7 @@ def hr_application_management_view(request): corp_applications = base_app_query.filter(form=app_form).filter(approved=None).order_by('-created') finished_corp_applications = base_app_query.filter(form=app_form).filter( approved__in=[True, False]).order_by('-created') - logger.debug("Retrieved %s personal, %s corp applications for %s" % ( + logger.debug("Retrieved {} personal, {} corp applications for {}".format( len(request.user.applications.all()), len(corp_applications), request.user)) context = { 'personal_apps': request.user.applications.all(), @@ -57,7 +57,7 @@ def hr_application_create_view(request, form_id=None): app_form = get_object_or_404(ApplicationForm, id=form_id) if request.method == "POST": if Application.objects.filter(user=request.user).filter(form=app_form).exists(): - logger.warn("User %s attempting to duplicate application to %s" % (request.user, app_form.corp)) + logger.warn(f"User {request.user} attempting to duplicate application to {app_form.corp}") else: application = Application(user=request.user, form=app_form) application.save() @@ -65,7 +65,7 @@ def hr_application_create_view(request, form_id=None): response = ApplicationResponse(question=question, application=application) response.answer = "\n".join(request.POST.getlist(str(question.pk), "")) response.save() - logger.info("%s created %s" % (request.user, application)) + logger.info(f"{request.user} created {application}") return redirect('hrapplications:personal_view', application.id) else: questions = app_form.questions.all() @@ -80,7 +80,7 @@ def hr_application_create_view(request, form_id=None): @login_required def hr_application_personal_view(request, app_id): - logger.debug("hr_application_personal_view called by user %s for app id %s" % (request.user, app_id)) + logger.debug(f"hr_application_personal_view called by user {request.user} for app id {app_id}") app = get_object_or_404(Application, pk=app_id) if app.user == request.user: context = { @@ -92,29 +92,29 @@ def hr_application_personal_view(request, app_id): } return render(request, 'hrapplications/view.html', context=context) else: - logger.warn("User %s not authorized to view %s" % (request.user, app)) + logger.warn(f"User {request.user} not authorized to view {app}") return redirect('hrapplications:personal_view') @login_required def hr_application_personal_removal(request, app_id): - logger.debug("hr_application_personal_removal called by user %s for app id %s" % (request.user, app_id)) + logger.debug(f"hr_application_personal_removal called by user {request.user} for app id {app_id}") app = get_object_or_404(Application, pk=app_id) if app.user == request.user: if app.approved is None: - logger.info("User %s deleting %s" % (request.user, app)) + logger.info(f"User {request.user} deleting {app}") app.delete() else: - logger.warn("User %s attempting to delete reviewed app %s" % (request.user, app)) + logger.warn(f"User {request.user} attempting to delete reviewed app {app}") else: - logger.warn("User %s not authorized to delete %s" % (request.user, app)) + logger.warn(f"User {request.user} not authorized to delete {app}") return redirect('hrapplications:index') @login_required @permission_required('auth.human_resources') def hr_application_view(request, app_id): - logger.debug("hr_application_view called by user %s for app id %s" % (request.user, app_id)) + logger.debug(f"hr_application_view called by user {request.user} for app id {app_id}") try: app = Application.objects.prefetch_related('responses', 'comments', 'comments__user').get(pk=app_id) except Application.DoesNotExist: @@ -129,7 +129,7 @@ def hr_application_view(request, app_id): comment.user = request.user comment.text = form.cleaned_data['comment'] comment.save() - logger.info("Saved comment by user %s to %s" % (request.user, app)) + logger.info(f"Saved comment by user {request.user} to {app}") return redirect('hrapplications:view', app_id) else: logger.warn("User %s does not have permission to add ApplicationComments" % request.user) @@ -151,9 +151,9 @@ def hr_application_view(request, app_id): @permission_required('auth.human_resources') @permission_required('hrapplications.delete_application') def hr_application_remove(request, app_id): - logger.debug("hr_application_remove called by user %s for app id %s" % (request.user, app_id)) + logger.debug(f"hr_application_remove called by user {request.user} for app id {app_id}") app = get_object_or_404(Application, pk=app_id) - logger.info("User %s deleting %s" % (request.user, app)) + logger.info(f"User {request.user} deleting {app}") app.delete() notify(app.user, "Application Deleted", message="Your application to %s was deleted." % app.form.corp) return redirect('hrapplications:index') @@ -163,15 +163,15 @@ def hr_application_remove(request, app_id): @permission_required('auth.human_resources') @permission_required('hrapplications.approve_application') def hr_application_approve(request, app_id): - logger.debug("hr_application_approve called by user %s for app id %s" % (request.user, app_id)) + logger.debug(f"hr_application_approve called by user {request.user} for app id {app_id}") app = get_object_or_404(Application, pk=app_id) if request.user.is_superuser or request.user == app.reviewer: - logger.info("User %s approving %s" % (request.user, app)) + logger.info(f"User {request.user} approving {app}") app.approved = True app.save() notify(app.user, "Application Accepted", message="Your application to %s has been approved." % app.form.corp, level="success") else: - logger.warn("User %s not authorized to approve %s" % (request.user, app)) + logger.warn(f"User {request.user} not authorized to approve {app}") return redirect('hrapplications:index') @@ -179,15 +179,15 @@ def hr_application_approve(request, app_id): @permission_required('auth.human_resources') @permission_required('hrapplications.reject_application') def hr_application_reject(request, app_id): - logger.debug("hr_application_reject called by user %s for app id %s" % (request.user, app_id)) + logger.debug(f"hr_application_reject called by user {request.user} for app id {app_id}") app = get_object_or_404(Application, pk=app_id) if request.user.is_superuser or request.user == app.reviewer: - logger.info("User %s rejecting %s" % (request.user, app)) + logger.info(f"User {request.user} rejecting {app}") app.approved = False app.save() notify(app.user, "Application Rejected", message="Your application to %s has been rejected." % app.form.corp, level="danger") else: - logger.warn("User %s not authorized to reject %s" % (request.user, app)) + logger.warn(f"User {request.user} not authorized to reject {app}") return redirect('hrapplications:index') @@ -200,8 +200,8 @@ def hr_application_search(request): logger.debug("Request type POST contains form valid: %s" % form.is_valid()) if form.is_valid(): searchstring = form.cleaned_data['search_string'].lower() - applications = set([]) - logger.debug("Searching for application with character name %s for user %s" % (searchstring, request.user)) + applications = set() + logger.debug(f"Searching for application with character name {searchstring} for user {request.user}") app_list = Application.objects.all() if not request.user.is_superuser: try: @@ -237,15 +237,15 @@ def hr_application_search(request): @login_required @permission_required('auth.human_resources') def hr_application_mark_in_progress(request, app_id): - logger.debug("hr_application_mark_in_progress called by user %s for app id %s" % (request.user, app_id)) + logger.debug(f"hr_application_mark_in_progress called by user {request.user} for app id {app_id}") app = get_object_or_404(Application, pk=app_id) if not app.reviewer: - logger.info("User %s marking %s in progress" % (request.user, app)) + logger.info(f"User {request.user} marking {app} in progress") app.reviewer = request.user app.reviewer_character = request.user.profile.main_character app.save() - notify(app.user, "Application In Progress", message="Your application to %s is being reviewed by %s" % (app.form.corp, app.reviewer_str)) + notify(app.user, "Application In Progress", message=f"Your application to {app.form.corp} is being reviewed by {app.reviewer_str}") else: logger.warn( - "User %s unable to mark %s in progress: already being reviewed by %s" % (request.user, app, app.reviewer)) + f"User {request.user} unable to mark {app} in progress: already being reviewed by {app.reviewer}") return redirect("hrapplications:view", app_id) diff --git a/allianceauth/notifications/handlers.py b/allianceauth/notifications/handlers.py index 20628a4a..b42aa09f 100644 --- a/allianceauth/notifications/handlers.py +++ b/allianceauth/notifications/handlers.py @@ -25,7 +25,7 @@ class NotificationHandler(logging.Handler): for user in users: notify( user, - "%s [%s:%s]" % (record.levelname, record.funcName, record.lineno), + f"{record.levelname} [{record.funcName}:{record.lineno}]", level=Notification.Level.from_old_name(record.levelname), message=message ) diff --git a/allianceauth/notifications/migrations/0001_initial.py b/allianceauth/notifications/migrations/0001_initial.py index 659fe6c0..867ca680 100644 --- a/allianceauth/notifications/migrations/0001_initial.py +++ b/allianceauth/notifications/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:40 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/notifications/migrations/0002_auto_20160910_1649.py b/allianceauth/notifications/migrations/0002_auto_20160910_1649.py index d6d1e9e8..f508b1b4 100644 --- a/allianceauth/notifications/migrations/0002_auto_20160910_1649.py +++ b/allianceauth/notifications/migrations/0002_auto_20160910_1649.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-10 16:49 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/notifications/migrations/0003_make_strings_more_stringy.py b/allianceauth/notifications/migrations/0003_make_strings_more_stringy.py index 700b5150..3ce2a64d 100644 --- a/allianceauth/notifications/migrations/0003_make_strings_more_stringy.py +++ b/allianceauth/notifications/migrations/0003_make_strings_more_stringy.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:35 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/notifications/models.py b/allianceauth/notifications/models.py index 55274d34..dd77d0ff 100644 --- a/allianceauth/notifications/models.py +++ b/allianceauth/notifications/models.py @@ -59,7 +59,7 @@ class Notification(models.Model): objects = NotificationManager() def __str__(self) -> str: - return "%s: %s" % (self.user, self.title) + return f"{self.user}: {self.title}" def save(self, *args, **kwargs): # overriden save to ensure cache is invaidated on very call diff --git a/allianceauth/notifications/tests/test_managers.py b/allianceauth/notifications/tests/test_managers.py index 7f62a752..19d40161 100644 --- a/allianceauth/notifications/tests/test_managers.py +++ b/allianceauth/notifications/tests/test_managers.py @@ -26,7 +26,7 @@ class TestQuerySet(TestCase): Notification.objects.notify_user(self.user_1, 'dummy_1') Notification.objects.notify_user(self.user_2, 'dummy_2') Notification.objects.update(viewed=True) - self.assertEquals(mock_invalidate_user_notification_cache.call_count, 2) + self.assertEqual(mock_invalidate_user_notification_cache.call_count, 2) class TestUserNotify(TestCase): @@ -123,19 +123,19 @@ class TestMaxNotificationsPerUser(TestCase): def test_reset_to_default_if_not_defined(self): result = Notification.objects._max_notifications_per_user() expected = NOTIFICATIONS_MAX_PER_USER_DEFAULT - self.assertEquals(result, expected) + self.assertEqual(result, expected) @override_settings(NOTIFICATIONS_MAX_PER_USER='11') def test_reset_to_default_if_not_int(self): result = Notification.objects._max_notifications_per_user() expected = NOTIFICATIONS_MAX_PER_USER_DEFAULT - self.assertEquals(result, expected) + self.assertEqual(result, expected) @override_settings(NOTIFICATIONS_MAX_PER_USER=-1) def test_reset_to_default_if_lt_zero(self): result = Notification.objects._max_notifications_per_user() expected = NOTIFICATIONS_MAX_PER_USER_DEFAULT - self.assertEquals(result, expected) + self.assertEqual(result, expected) @patch('allianceauth.notifications.managers.cache') @@ -219,7 +219,7 @@ class TestUnreadCount(TestCase): def test_return_error_code_when_user_not_found(self, mock_cache): mock_cache.get.return_value = None - invalid_user_id = max([user.pk for user in User.objects.all()]) + 1 + invalid_user_id = max(user.pk for user in User.objects.all()) + 1 result = Notification.objects.user_unread_count(invalid_user_id) expected = -1 self.assertEqual(result, expected) diff --git a/allianceauth/notifications/tests/test_models.py b/allianceauth/notifications/tests/test_models.py index 554ce4ec..b291f2c8 100644 --- a/allianceauth/notifications/tests/test_models.py +++ b/allianceauth/notifications/tests/test_models.py @@ -29,7 +29,7 @@ class TestUserNotify(TestCase): def test_save_will_invalidate_cache(self, mock_invalidate_user_notification_cache): obj = Notification.objects.notify_user(self.user, 'dummy') self.assertTrue(Notification.objects.filter(pk=obj.pk).exists()) - self.assertEquals(mock_invalidate_user_notification_cache.call_count, 1) + self.assertEqual(mock_invalidate_user_notification_cache.call_count, 1) @patch(MODULE_PATH + '.Notification.objects.invalidate_user_notification_cache') def test_delete_will_invalidate_cache( @@ -38,7 +38,7 @@ class TestUserNotify(TestCase): obj = Notification.objects.notify_user(self.user, 'dummy') obj.delete() self.assertFalse(Notification.objects.filter(pk=obj.pk).exists()) - self.assertEquals(mock_invalidate_user_notification_cache.call_count, 2) + self.assertEqual(mock_invalidate_user_notification_cache.call_count, 2) def test_can_view(self): obj = Notification.objects.notify_user(self.user, 'dummy') diff --git a/allianceauth/optimer/migrations/0001_initial.py b/allianceauth/optimer/migrations/0001_initial.py index 2efae2a7..7e57fa8a 100644 --- a/allianceauth/optimer/migrations/0001_initial.py +++ b/allianceauth/optimer/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:40 -from __future__ import unicode_literals import datetime from django.db import migrations, models diff --git a/allianceauth/optimer/migrations/0002_auto_20170413_0442.py b/allianceauth/optimer/migrations/0002_auto_20170413_0442.py index e9d0267e..e31663ef 100644 --- a/allianceauth/optimer/migrations/0002_auto_20170413_0442.py +++ b/allianceauth/optimer/migrations/0002_auto_20170413_0442.py @@ -1,5 +1,4 @@ # Generated by Django 1.11 on 2017-04-13 04:42 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/optimer/migrations/0003_make_strings_more_stringy.py b/allianceauth/optimer/migrations/0003_make_strings_more_stringy.py index 6f67ffb4..e0e8876b 100644 --- a/allianceauth/optimer/migrations/0003_make_strings_more_stringy.py +++ b/allianceauth/optimer/migrations/0003_make_strings_more_stringy.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:35 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/optimer/migrations/0004_on_delete.py b/allianceauth/optimer/migrations/0004_on_delete.py index 69dcd1cf..f07883c3 100644 --- a/allianceauth/optimer/migrations/0004_on_delete.py +++ b/allianceauth/optimer/migrations/0004_on_delete.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/optimer/views.py b/allianceauth/optimer/views.py index 96831147..787c2e19 100644 --- a/allianceauth/optimer/views.py +++ b/allianceauth/optimer/views.py @@ -51,7 +51,7 @@ def add_optimer_view(request): op.create_time = post_time op.eve_character = character op.save() - logger.info("User %s created op timer with name %s" % (request.user, op.operation_name)) + logger.info(f"User {request.user} created op timer with name {op.operation_name}") messages.success(request, _('Created operation timer for %(opname)s.') % {"opname": op.operation_name}) return redirect("optimer:view") else: @@ -66,10 +66,10 @@ def add_optimer_view(request): @login_required @permission_required('auth.optimer_management') def remove_optimer(request, optimer_id): - logger.debug("remove_optimer called by user %s for operation id %s" % (request.user, optimer_id)) + logger.debug(f"remove_optimer called by user {request.user} for operation id {optimer_id}") op = get_object_or_404(OpTimer, id=optimer_id) op.delete() - logger.info("Deleting optimer id %s by user %s" % (optimer_id, request.user)) + logger.info(f"Deleting optimer id {optimer_id} by user {request.user}") messages.success(request, _('Removed operation timer for %(opname)s.') % {"opname": op.operation_name}) return redirect("optimer:view") @@ -77,7 +77,7 @@ def remove_optimer(request, optimer_id): @login_required @permission_required('auth.optimer_management') def edit_optimer(request, optimer_id): - logger.debug("edit_optimer called by user %s for optimer id %s" % (request.user, optimer_id)) + logger.debug(f"edit_optimer called by user {request.user} for optimer id {optimer_id}") op = get_object_or_404(OpTimer, id=optimer_id) if request.method == 'POST': form = OpForm(request.POST) @@ -91,7 +91,7 @@ def edit_optimer(request, optimer_id): op.operation_name = form.cleaned_data['operation_name'] op.fc = form.cleaned_data['fc'] op.eve_character = character - logger.info("User %s updating optimer id %s " % (request.user, optimer_id)) + logger.info(f"User {request.user} updating optimer id {optimer_id} ") op.save() messages.success(request, _('Saved changes to operation timer for %(opname)s.') % {"opname": op.operation_name}) return redirect("optimer:view") diff --git a/allianceauth/permissions_tool/migrations/0001_initial.py b/allianceauth/permissions_tool/migrations/0001_initial.py index 33b88a53..5ebf5a59 100644 --- a/allianceauth/permissions_tool/migrations/0001_initial.py +++ b/allianceauth/permissions_tool/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-06 08:58 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/permissions_tool/views.py b/allianceauth/permissions_tool/views.py index 11c74822..e845a466 100644 --- a/allianceauth/permissions_tool/views.py +++ b/allianceauth/permissions_tool/views.py @@ -43,7 +43,7 @@ def permissions_overview(request): @login_required @permission_required('permissions_tool.audit_permissions') def permissions_audit(request, app_label, model, codename): - logger.debug("permissions_audit called by user {} on {}:{}:{}".format(request.user, app_label, model, codename)) + logger.debug(f"permissions_audit called by user {request.user} on {app_label}:{model}:{codename}") try: perm = Permission.objects\ .prefetch_related('group_set', 'user_set', 'state_set', diff --git a/allianceauth/services/abstract.py b/allianceauth/services/abstract.py index 51614c91..d6e500e0 100644 --- a/allianceauth/services/abstract.py +++ b/allianceauth/services/abstract.py @@ -34,7 +34,7 @@ class AbstractServiceModel(models.Model): ) def __init__(self, *args, **kwargs): - super(AbstractServiceModel, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.credentials = OrderedDict() # Should be set with a dict of service credentials (username, password etc) when changed @@ -65,7 +65,7 @@ class ServiceCredentialsViewMixin: class BaseCreatePasswordServiceAccountView(BaseServiceView, ServiceCredentialsViewMixin): def get(self, request): - logger.debug("{} called by user {}".format(self.__class__.__name__, request.user)) + logger.debug(f"{self.__class__.__name__} called by user {request.user}") try: svc_obj = self.model.objects.create(user=request.user) except IntegrityError: @@ -98,9 +98,9 @@ class BaseSetPasswordServiceAccountView(ServicesCRUDMixin, BaseServiceView, Upda form_class = ServicePasswordModelForm # You should overload this with a subclass def post(self, request, *args, **kwargs): - result = super(BaseSetPasswordServiceAccountView, self).post(request, *args, **kwargs) + result = super().post(request, *args, **kwargs) if self.get_form().is_valid(): - messages.success(request, _("Successfully set your {} password".format(self.service_name))) + messages.success(request, _(f"Successfully set your {self.service_name} password")) return result diff --git a/allianceauth/services/admin.py b/allianceauth/services/admin.py index b10c6e8a..e16bfc08 100644 --- a/allianceauth/services/admin.py +++ b/allianceauth/services/admin.py @@ -52,7 +52,7 @@ class ServicesUserAdmin(admin.ModelAdmin): class NameFormatConfigForm(forms.ModelForm): def __init__(self, *args, **kwargs): - super(NameFormatConfigForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) SERVICE_CHOICES = \ [(s.name, s.name) for h in hooks.get_hooks('services_hook') for s in [h()]] if self.instance.id: diff --git a/allianceauth/services/forms.py b/allianceauth/services/forms.py index 522837f4..1eda557e 100644 --- a/allianceauth/services/forms.py +++ b/allianceauth/services/forms.py @@ -37,7 +37,7 @@ class ServicePasswordModelForm(forms.ModelForm): return password def save(self, commit=True): - svc_obj = super(ServicePasswordModelForm, self).save(commit=False) + svc_obj = super().save(commit=False) svc_obj.update_password(self.cleaned_data['password']) if commit: svc_obj.save() diff --git a/allianceauth/services/migrations/0001_squashed_0003_delete_groupcache.py b/allianceauth/services/migrations/0001_squashed_0003_delete_groupcache.py index 395521ba..7c37fc47 100644 --- a/allianceauth/services/migrations/0001_squashed_0003_delete_groupcache.py +++ b/allianceauth/services/migrations/0001_squashed_0003_delete_groupcache.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.5 on 2017-10-07 03:55 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations diff --git a/allianceauth/services/migrations/0002_nameformatter.py b/allianceauth/services/migrations/0002_nameformatter.py index e3533817..7b5fa1ab 100644 --- a/allianceauth/services/migrations/0002_nameformatter.py +++ b/allianceauth/services/migrations/0002_nameformatter.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.5 on 2017-10-07 06:43 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/services/models.py b/allianceauth/services/models.py index 4a1ec7ee..9bd1117b 100644 --- a/allianceauth/services/models.py +++ b/allianceauth/services/models.py @@ -27,6 +27,6 @@ class NameFormatConfig(models.Model): ) def __str__(self): - return '%s: %s' % ( + return '{}: {}'.format( self.service_name, ', '.join([str(x) for x in self.states.all()]) ) diff --git a/allianceauth/services/modules/discord/discord_client/helpers.py b/allianceauth/services/modules/discord/discord_client/helpers.py index 02cce05d..859b3d01 100644 --- a/allianceauth/services/modules/discord/discord_client/helpers.py +++ b/allianceauth/services/modules/discord/discord_client/helpers.py @@ -31,8 +31,7 @@ class DiscordRoles: return hash(tuple(sorted(self._roles.keys()))) def __iter__(self): - for role in self._roles.values(): - yield role + yield from self._roles.values() def __contains__(self, item) -> bool: return int(item) in self._roles diff --git a/allianceauth/services/modules/discord/discord_client/tests/test_client.py b/allianceauth/services/modules/discord/discord_client/tests/test_client.py index 4f540723..acc57fac 100644 --- a/allianceauth/services/modules/discord/discord_client/tests/test_client.py +++ b/allianceauth/services/modules/discord/discord_client/tests/test_client.py @@ -1400,7 +1400,7 @@ class TestRedisDecode(TestCase): def test_decode_string(self): self.assertEqual( - DiscordClient._redis_decode('MyTest123'.encode('utf8')), 'MyTest123' + DiscordClient._redis_decode(b'MyTest123'), 'MyTest123' ) def test_decode_bool(self): diff --git a/allianceauth/services/modules/discord/migrations/0001_initial.py b/allianceauth/services/modules/discord/migrations/0001_initial.py index ca627630..932bb5fc 100644 --- a/allianceauth/services/modules/discord/migrations/0001_initial.py +++ b/allianceauth/services/modules/discord/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:14 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/discord/migrations/0002_service_permissions.py b/allianceauth/services/modules/discord/migrations/0002_service_permissions.py index 8779615d..f10a1cf6 100644 --- a/allianceauth/services/modules/discord/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/discord/migrations/0002_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_discord') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if DiscordUser.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_DISCORD'), False): + getattr(settings, 'ENABLE_AUTH_DISCORD', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if DiscordUser.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_DISCORD'), False): + getattr(settings, 'ENABLE_BLUE_DISCORD', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/discord/models.py b/allianceauth/services/modules/discord/models.py index d74aecc8..321cd183 100644 --- a/allianceauth/services/modules/discord/models.py +++ b/allianceauth/services/modules/discord/models.py @@ -123,7 +123,7 @@ class DiscordUser(models.Model): ) if not guild_roles.has_roles(member_info['roles']): raise RuntimeError( - 'Member %s has unknown roles: %s' % ( + 'Member {} has unknown roles: {}'.format( self.user, set(member_info['roles']).difference(guild_roles.ids()) ) diff --git a/allianceauth/services/modules/discord/tests/test_integration.py b/allianceauth/services/modules/discord/tests/test_integration.py index 4a944693..e69f6a4d 100644 --- a/allianceauth/services/modules/discord/tests/test_integration.py +++ b/allianceauth/services/modules/discord/tests/test_integration.py @@ -395,12 +395,12 @@ class StateTestCase(TestCase): self.assertIsNotNone(self.user.discord) higher_state.member_characters.add(self.test_character) self._refresh_user() - self.assertEquals(higher_state, self.user.profile.state) + self.assertEqual(higher_state, self.user.profile.state) with self.assertRaises(DiscordUser.DoesNotExist): self.user.discord higher_state.member_characters.clear() self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) with self.assertRaises(DiscordUser.DoesNotExist): self.user.discord @@ -419,15 +419,15 @@ class StateTestCase(TestCase): self.assertIsNotNone(self.user.discord) lower_state.member_characters.add(self.test_character) self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) self.member_state.member_characters.clear() self._refresh_user() - self.assertEquals(lower_state, self.user.profile.state) + self.assertEqual(lower_state, self.user.profile.state) with self.assertRaises(DiscordUser.DoesNotExist): self.user.discord self.member_state.member_characters.add(self.test_character) self._refresh_user() - self.assertEquals(self.member_state, self.user.profile.state) + self.assertEqual(self.member_state, self.user.profile.state) with self.assertRaises(DiscordUser.DoesNotExist): self.user.discord diff --git a/allianceauth/services/modules/discord/utils.py b/allianceauth/services/modules/discord/utils.py index 98067d03..26ffbe00 100644 --- a/allianceauth/services/modules/discord/utils.py +++ b/allianceauth/services/modules/discord/utils.py @@ -10,11 +10,11 @@ logger = logging.getLogger(__name__) class LoggerAddTag(logging.LoggerAdapter): """add custom tag to a logger""" def __init__(self, logger, prefix): - super(LoggerAddTag, self).__init__(logger, {}) + super().__init__(logger, {}) self.prefix = prefix def process(self, msg, kwargs): - return '[%s] %s' % (self.prefix, msg), kwargs + return f'[{self.prefix}] {msg}', kwargs def clean_setting( @@ -80,7 +80,7 @@ def set_logger_to_file(logger_name: str, name: str) -> object: '%(asctime)s - %(levelname)s - %(module)s:%(funcName)s - %(message)s' ) path = os.path.splitext(name)[0] - f_handler = logging.FileHandler('{}.log'.format(path), 'w+') + f_handler = logging.FileHandler(f'{path}.log', 'w+') f_handler.setFormatter(f_format) logger = logging.getLogger(logger_name) logger.level = logging.DEBUG diff --git a/allianceauth/services/modules/discourse/auth_hooks.py b/allianceauth/services/modules/discourse/auth_hooks.py index 514e0c98..744dbe4c 100644 --- a/allianceauth/services/modules/discourse/auth_hooks.py +++ b/allianceauth/services/modules/discourse/auth_hooks.py @@ -21,16 +21,16 @@ class DiscourseService(ServicesHook): self.name_format = '{character_name}' def delete_user(self, user, notify_user=False): - logger.debug('Deleting user %s %s account' % (user, self.name)) + logger.debug(f'Deleting user {user} {self.name} account') return DiscourseTasks.delete_user(user, notify_user=notify_user) def update_groups(self, user): - logger.debug('Processing %s groups for %s' % (self.name, user)) + logger.debug(f'Processing {self.name} groups for {user}') if DiscourseTasks.has_account(user): DiscourseTasks.update_groups.delay(user.pk) def validate_user(self, user): - logger.debug('Validating user %s %s account' % (user, self.name)) + logger.debug(f'Validating user {user} {self.name} account') if DiscourseTasks.has_account(user) and not self.service_active_for_user(user): self.delete_user(user, notify_user=True) diff --git a/allianceauth/services/modules/discourse/manager.py b/allianceauth/services/modules/discourse/manager.py index bdf69cea..03cbbdee 100644 --- a/allianceauth/services/modules/discourse/manager.py +++ b/allianceauth/services/modules/discourse/manager.py @@ -16,7 +16,7 @@ class DiscourseError(Exception): self.errors = errors def __str__(self): - return "API execution failed.\nErrors: %s\nEndpoint: %s" % (self.errors, self.endpoint) + return f"API execution failed.\nErrors: {self.errors}\nEndpoint: {self.endpoint}" class DiscourseManager: @@ -165,7 +165,7 @@ class DiscourseManager: @staticmethod def _sanitize_groupname(name): - name = re.sub('[^\w]', '', name) + name = re.sub(r'[^\w]', '', name) name = DiscourseManager._sanitize_name(name) if len(name) < 3: name = "Group " + name @@ -176,7 +176,7 @@ class DiscourseManager: groups = [DiscourseManager._sanitize_groupname(user.profile.state.name)] for g in user.groups.all(): groups.append(DiscourseManager._sanitize_groupname(str(g))) - logger.debug("Updating discourse user %s groups to %s" % (user, groups)) + logger.debug(f"Updating discourse user {user} groups to {groups}") group_dict = DiscourseManager.__generate_group_dict(groups) inv_group_dict = {v: k for k, v in group_dict.items()} discord_user = DiscourseManager.__get_user_by_external(user.pk) @@ -187,12 +187,12 @@ class DiscourseManager: rem_groups = [x for x in user_groups if x not in inv_group_dict] if add_groups: logger.info( - "Updating discourse user %s groups: adding %s" % (username, add_groups)) + f"Updating discourse user {username} groups: adding {add_groups}") for g in add_groups: DiscourseManager.__add_user_to_group(g, username) if rem_groups: logger.info( - "Updating discourse user %s groups: removing %s" % (username, rem_groups)) + f"Updating discourse user {username} groups: removing {rem_groups}") for g in rem_groups: DiscourseManager.__remove_user_from_group(g, uid) diff --git a/allianceauth/services/modules/discourse/migrations/0001_initial.py b/allianceauth/services/modules/discourse/migrations/0001_initial.py index a7b9109f..f9e0139c 100644 --- a/allianceauth/services/modules/discourse/migrations/0001_initial.py +++ b/allianceauth/services/modules/discourse/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:15 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/discourse/migrations/0002_service_permissions.py b/allianceauth/services/modules/discourse/migrations/0002_service_permissions.py index d18939f6..bde79988 100644 --- a/allianceauth/services/modules/discourse/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/discourse/migrations/0002_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_discourse') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if DiscourseUser.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_DISCOURSE'), False): + getattr(settings, 'ENABLE_AUTH_DISCOURSE', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if DiscourseUser.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_DISCOURSE'), False): + getattr(settings, 'ENABLE_BLUE_DISCOURSE', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/discourse/models.py b/allianceauth/services/modules/discourse/models.py index f4b2b871..22014cf9 100644 --- a/allianceauth/services/modules/discourse/models.py +++ b/allianceauth/services/modules/discourse/models.py @@ -14,5 +14,5 @@ class DiscourseUser(models.Model): class Meta: permissions = ( - ("access_discourse", u"Can access the Discourse service"), + ("access_discourse", "Can access the Discourse service"), ) diff --git a/allianceauth/services/modules/discourse/views.py b/allianceauth/services/modules/discourse/views.py index 76efd5d7..a777fbb7 100644 --- a/allianceauth/services/modules/discourse/views.py +++ b/allianceauth/services/modules/discourse/views.py @@ -93,4 +93,4 @@ def discourse_sso(request): # Redirect back to Discourse url = '%s/session/sso_login' % settings.DISCOURSE_URL - return redirect('%s?%s' % (url, query_string)) + return redirect(f'{url}?{query_string}') diff --git a/allianceauth/services/modules/ips4/manager.py b/allianceauth/services/modules/ips4/manager.py index 4683895e..40b1cad9 100644 --- a/allianceauth/services/modules/ips4/manager.py +++ b/allianceauth/services/modules/ips4/manager.py @@ -39,7 +39,7 @@ class Ips4Manager: cursor.execute(Ips4Manager.SQL_GET_ID, [username]) row = cursor.fetchone() if row is not None: - logger.debug("Got user id %s for username %s" % (row[0], username)) + logger.debug(f"Got user id {row[0]} for username {username}") return row[0] else: logger.error("username %s not found. Unable to determine id." % username) diff --git a/allianceauth/services/modules/ips4/migrations/0001_initial.py b/allianceauth/services/modules/ips4/migrations/0001_initial.py index 51485a67..83f3159f 100644 --- a/allianceauth/services/modules/ips4/migrations/0001_initial.py +++ b/allianceauth/services/modules/ips4/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:27 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/ips4/migrations/0002_service_permissions.py b/allianceauth/services/modules/ips4/migrations/0002_service_permissions.py index 558a48a7..17c0fc09 100644 --- a/allianceauth/services/modules/ips4/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/ips4/migrations/0002_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_ips4') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if Ips4User.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_IPS4'), False): + getattr(settings, 'ENABLE_AUTH_IPS4', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if Ips4User.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_IPS4'), False): + getattr(settings, 'ENABLE_BLUE_IPS4', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/ips4/models.py b/allianceauth/services/modules/ips4/models.py index 407e243a..56d83263 100644 --- a/allianceauth/services/modules/ips4/models.py +++ b/allianceauth/services/modules/ips4/models.py @@ -15,5 +15,5 @@ class Ips4User(models.Model): class Meta: permissions = ( - ("access_ips4", u"Can access the IPS4 service"), + ("access_ips4", "Can access the IPS4 service"), ) diff --git a/allianceauth/services/modules/ips4/tests.py b/allianceauth/services/modules/ips4/tests.py index e568f0bd..48e7ffa4 100644 --- a/allianceauth/services/modules/ips4/tests.py +++ b/allianceauth/services/modules/ips4/tests.py @@ -143,7 +143,7 @@ class Ips4ManagerTestCase(TestCase): password = self.manager._Ips4Manager__generate_random_pass() self.assertEqual(len(password), 16) - self.assertIsInstance(password, type('')) + self.assertIsInstance(password, str) def test_gen_pwhash(self): pwhash = self.manager._gen_pwhash('test') diff --git a/allianceauth/services/modules/ips4/views.py b/allianceauth/services/modules/ips4/views.py index 05aff3b8..a1cc1b1c 100644 --- a/allianceauth/services/modules/ips4/views.py +++ b/allianceauth/services/modules/ips4/views.py @@ -20,7 +20,7 @@ ACCESS_PERM = 'ips4.access_ips4' def activate_ips4(request): logger.debug("activate_ips4 called by user %s" % request.user) character = request.user.profile.main_character - logger.debug("Adding IPS4 user for user %s with main character %s" % (request.user, character)) + logger.debug(f"Adding IPS4 user for user {request.user} with main character {character}") result = Ips4Manager.add_user(Ips4Tasks.get_username(request.user), request.user.email) # if empty we failed if result[0] != "" and not Ips4Tasks.has_account(request.user): diff --git a/allianceauth/services/modules/mumble/auth_hooks.py b/allianceauth/services/modules/mumble/auth_hooks.py index 71f71e21..efc8df33 100644 --- a/allianceauth/services/modules/mumble/auth_hooks.py +++ b/allianceauth/services/modules/mumble/auth_hooks.py @@ -25,7 +25,7 @@ class MumbleService(ServicesHook): self.name_format = '[{corp_ticker}]{character_name}' def delete_user(self, user, notify_user=False): - logging.debug("Deleting user %s %s account" % (user, self.name)) + logging.debug(f"Deleting user {user} {self.name} account") try: if user.mumble.delete(): if notify_user: @@ -36,12 +36,12 @@ class MumbleService(ServicesHook): logging.debug("User does not have a mumble account") def update_groups(self, user): - logger.debug("Updating %s groups for %s" % (self.name, user)) + logger.debug(f"Updating {self.name} groups for {user}") if MumbleTasks.has_account(user): MumbleTasks.update_groups.delay(user.pk) def sync_nickname(self, user): - logger.debug("Updating %s nickname for %s" % (self.name, user)) + logger.debug(f"Updating {self.name} nickname for {user}") if MumbleTasks.has_account(user): MumbleTasks.update_display_name.apply_async(args=[user.pk], countdown=5) # cooldown on this task to ensure DB clean when syncing diff --git a/allianceauth/services/modules/mumble/migrations/0001_initial.py b/allianceauth/services/modules/mumble/migrations/0001_initial.py index 1345f9a3..ee74dfa1 100644 --- a/allianceauth/services/modules/mumble/migrations/0001_initial.py +++ b/allianceauth/services/modules/mumble/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 00:58 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/services/modules/mumble/migrations/0002_auto_20161212_0100.py b/allianceauth/services/modules/mumble/migrations/0002_auto_20161212_0100.py index cff8821b..2a253099 100644 --- a/allianceauth/services/modules/mumble/migrations/0002_auto_20161212_0100.py +++ b/allianceauth/services/modules/mumble/migrations/0002_auto_20161212_0100.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 01:00 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/services/modules/mumble/migrations/0003_mumbleuser_user.py b/allianceauth/services/modules/mumble/migrations/0003_mumbleuser_user.py index e8857aca..9745e67e 100644 --- a/allianceauth/services/modules/mumble/migrations/0003_mumbleuser_user.py +++ b/allianceauth/services/modules/mumble/migrations/0003_mumbleuser_user.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:31 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/mumble/migrations/0004_auto_20161214_1024.py b/allianceauth/services/modules/mumble/migrations/0004_auto_20161214_1024.py index 2491311d..b74ebd46 100644 --- a/allianceauth/services/modules/mumble/migrations/0004_auto_20161214_1024.py +++ b/allianceauth/services/modules/mumble/migrations/0004_auto_20161214_1024.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.4 on 2016-12-14 10:24 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/mumble/migrations/0005_mumbleuser_hashfn.py b/allianceauth/services/modules/mumble/migrations/0005_mumbleuser_hashfn.py index a0244978..78fc8657 100644 --- a/allianceauth/services/modules/mumble/migrations/0005_mumbleuser_hashfn.py +++ b/allianceauth/services/modules/mumble/migrations/0005_mumbleuser_hashfn.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.4 on 2017-01-23 10:28 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/services/modules/mumble/migrations/0006_service_permissions.py b/allianceauth/services/modules/mumble/migrations/0006_service_permissions.py index d3f4897f..1b64ecc9 100644 --- a/allianceauth/services/modules/mumble/migrations/0006_service_permissions.py +++ b/allianceauth/services/modules/mumble/migrations/0006_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_mumble') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if MumbleUser.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_MUMBLE'), False): + getattr(settings, 'ENABLE_AUTH_MUMBLE', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if MumbleUser.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_MUMBLE'), False): + getattr(settings, 'ENABLE_BLUE_MUMBLE', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/mumble/migrations/0007_not_null_user.py b/allianceauth/services/modules/mumble/migrations/0007_not_null_user.py index 1a19da28..df12bd95 100644 --- a/allianceauth/services/modules/mumble/migrations/0007_not_null_user.py +++ b/allianceauth/services/modules/mumble/migrations/0007_not_null_user.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.6 on 2017-10-09 09:19 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/mumble/models.py b/allianceauth/services/modules/mumble/models.py index f335064a..75d3f269 100644 --- a/allianceauth/services/modules/mumble/models.py +++ b/allianceauth/services/modules/mumble/models.py @@ -38,16 +38,16 @@ class MumbleManager(models.Manager): def create(self, user): try: username = self.get_username(user) - logger.debug("Creating mumble user with username {}".format(username)) + logger.debug(f"Creating mumble user with username {username}") username_clean = self.sanitise_username(username) display_name = self.get_display_name(user) password = self.generate_random_pass() pwhash = self.gen_pwhash(password) logger.debug("Proceeding with mumble user creation: clean username {}, pwhash starts with {}".format( username_clean, pwhash[0:5])) - logger.info("Creating mumble user {}".format(username_clean)) + logger.info(f"Creating mumble user {username_clean}") - result = super(MumbleManager, self).create(user=user, username=username_clean, + result = super().create(user=user, username=username_clean, pwhash=pwhash, hashfn=self.HASH_FN, display_name=display_name) result.update_groups() @@ -117,7 +117,7 @@ class MumbleUser(AbstractServiceModel): def update_password(self, password=None): init_password = password - logger.debug("Updating mumble user %s password.".format(self.user)) + logger.debug(f"Updating mumble user %s password.") if not password: password = MumbleManager.generate_random_pass() pwhash = MumbleManager.gen_pwhash(password) @@ -138,19 +138,19 @@ class MumbleUser(AbstractServiceModel): groups_str = [self.user.profile.state.name] for group in groups: groups_str.append(str(group.name)) - safe_groups = ','.join(set([g.replace(' ', '-') for g in groups_str])) - logger.info("Updating mumble user {} groups to {}".format(self.user, safe_groups)) + safe_groups = ','.join({g.replace(' ', '-') for g in groups_str}) + logger.info(f"Updating mumble user {self.user} groups to {safe_groups}") self.groups = safe_groups self.save() return True def update_display_name(self): - logger.info("Updating mumble user {} display name".format(self.user)) + logger.info(f"Updating mumble user {self.user} display name") self.display_name = MumbleManager.get_display_name(self.user) self.save() return True class Meta: permissions = ( - ("access_mumble", u"Can access the Mumble service"), + ("access_mumble", "Can access the Mumble service"), ) diff --git a/allianceauth/services/modules/mumble/tasks.py b/allianceauth/services/modules/mumble/tasks.py index 02406d75..5ce7c9c4 100644 --- a/allianceauth/services/modules/mumble/tasks.py +++ b/allianceauth/services/modules/mumble/tasks.py @@ -37,7 +37,7 @@ class MumbleTasks: logger.debug("Updated user %s mumble groups." % user) return True except MumbleUser.DoesNotExist: - logger.info("Mumble group sync failed for {}, user does not have a mumble account".format(user)) + logger.info(f"Mumble group sync failed for {user}, user does not have a mumble account") except: logger.exception("Mumble group sync failed for %s, retrying in 10 mins" % user) raise self.retry(countdown=60 * 10) @@ -57,7 +57,7 @@ class MumbleTasks: logger.debug("Updated user %s mumble display name." % user) return True except MumbleUser.DoesNotExist: - logger.info("Mumble display name sync failed for {}, user does not have a mumble account".format(user)) + logger.info(f"Mumble display name sync failed for {user}, user does not have a mumble account") except: logger.exception("Mumble display name sync failed for %s, retrying in 10 mins" % user) raise self.retry(countdown=60 * 10) diff --git a/allianceauth/services/modules/mumble/tests.py b/allianceauth/services/modules/mumble/tests.py index 8f0f74a2..e17d0267 100644 --- a/allianceauth/services/modules/mumble/tests.py +++ b/allianceauth/services/modules/mumble/tests.py @@ -203,7 +203,7 @@ class MumbleManagerTestCase(TestCase): password = self.manager.generate_random_pass() self.assertEqual(len(password), 16) - self.assertIsInstance(password, type('')) + self.assertIsInstance(password, str) def test_gen_pwhash(self): pwhash = self.manager.gen_pwhash('test') diff --git a/allianceauth/services/modules/openfire/auth_hooks.py b/allianceauth/services/modules/openfire/auth_hooks.py index c3520a35..91a71cd9 100644 --- a/allianceauth/services/modules/openfire/auth_hooks.py +++ b/allianceauth/services/modules/openfire/auth_hooks.py @@ -26,16 +26,16 @@ class OpenfireService(ServicesHook): return _("Jabber") def delete_user(self, user, notify_user=False): - logger.debug('Deleting user %s %s account' % (user, self.name)) + logger.debug(f'Deleting user {user} {self.name} account') return OpenfireTasks.delete_user(user, notify_user=notify_user) def validate_user(self, user): - logger.debug('Validating user %s %s account' % (user, self.name)) + logger.debug(f'Validating user {user} {self.name} account') if OpenfireTasks.has_account(user) and not self.service_active_for_user(user): self.delete_user(user, notify_user=True) def update_groups(self, user): - logger.debug('Updating %s groups for %s' % (self.name, user)) + logger.debug(f'Updating {self.name} groups for {user}') if OpenfireTasks.has_account(user): OpenfireTasks.update_groups.delay(user.pk) diff --git a/allianceauth/services/modules/openfire/manager.py b/allianceauth/services/modules/openfire/manager.py index f1caa1fe..d227af09 100755 --- a/allianceauth/services/modules/openfire/manager.py +++ b/allianceauth/services/modules/openfire/manager.py @@ -56,7 +56,7 @@ class OpenfireManager: @staticmethod def _sanitize_groupname(name): name = name.strip(' _').lower() - return re.sub('[^\w.-]', '', name) + return re.sub(r'[^\w.-]', '', name) @staticmethod def add_user(username): @@ -116,7 +116,7 @@ class OpenfireManager: @classmethod def update_user_groups(cls, username, groups): - logger.debug("Updating openfire user %s groups %s" % (username, groups)) + logger.debug(f"Updating openfire user {username} groups {groups}") s_groups = list(map(cls._sanitize_groupname, groups)) # Sanitized group names api = ofUsers(settings.OPENFIRE_ADDRESS, settings.OPENFIRE_SECRET_KEY) response = api.get_user_groups(username) @@ -126,7 +126,7 @@ class OpenfireManager: if isinstance(remote_groups, str): remote_groups = [remote_groups] remote_groups = list(map(cls._sanitize_groupname, remote_groups)) - logger.debug("Openfire user %s has groups %s" % (username, remote_groups)) + logger.debug(f"Openfire user {username} has groups {remote_groups}") add_groups = [] del_groups = [] for g in s_groups: @@ -136,7 +136,7 @@ class OpenfireManager: if g not in s_groups: del_groups.append(g) logger.info( - "Updating openfire groups for user %s - adding %s, removing %s" % (username, add_groups, del_groups)) + f"Updating openfire groups for user {username} - adding {add_groups}, removing {del_groups}") if add_groups: api.add_user_groups(username, add_groups) if del_groups: @@ -144,15 +144,15 @@ class OpenfireManager: @staticmethod def delete_user_groups(username, groups): - logger.debug("Deleting openfire groups %s from user %s" % (groups, username)) + logger.debug(f"Deleting openfire groups {groups} from user {username}") api = ofUsers(settings.OPENFIRE_ADDRESS, settings.OPENFIRE_SECRET_KEY) api.delete_user_groups(username, groups) - logger.info("Deleted groups %s from openfire user %s" % (groups, username)) + logger.info(f"Deleted groups {groups} from openfire user {username}") @classmethod def send_broadcast_message(cls, group_name, broadcast_message): s_group_name = cls._sanitize_groupname(group_name) - logger.debug("Sending jabber ping to group %s with message %s" % (s_group_name, broadcast_message)) + logger.debug(f"Sending jabber ping to group {s_group_name} with message {broadcast_message}") to_address = s_group_name + '@' + settings.BROADCAST_SERVICE_NAME + '.' + settings.JABBER_URL xmpp = PingBot(settings.BROADCAST_USER, settings.BROADCAST_USER_PASSWORD, to_address, broadcast_message) xmpp.register_plugin('xep_0030') # Service Discovery diff --git a/allianceauth/services/modules/openfire/migrations/0001_initial.py b/allianceauth/services/modules/openfire/migrations/0001_initial.py index d2d1d362..7d705897 100644 --- a/allianceauth/services/modules/openfire/migrations/0001_initial.py +++ b/allianceauth/services/modules/openfire/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:27 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/openfire/migrations/0002_service_permissions.py b/allianceauth/services/modules/openfire/migrations/0002_service_permissions.py index 3d55065c..7570cb4e 100644 --- a/allianceauth/services/modules/openfire/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/openfire/migrations/0002_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_openfire') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if OpenfireUser.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_JABBER'), False): + getattr(settings, 'ENABLE_AUTH_JABBER', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if OpenfireUser.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_JABBER'), False): + getattr(settings, 'ENABLE_BLUE_JABBER', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/openfire/models.py b/allianceauth/services/modules/openfire/models.py index 15cb4253..5299ed8d 100644 --- a/allianceauth/services/modules/openfire/models.py +++ b/allianceauth/services/modules/openfire/models.py @@ -13,5 +13,5 @@ class OpenfireUser(models.Model): class Meta: permissions = ( - ("access_openfire", u"Can access the Openfire service"), + ("access_openfire", "Can access the Openfire service"), ) diff --git a/allianceauth/services/modules/openfire/tasks.py b/allianceauth/services/modules/openfire/tasks.py index 3993b6b6..92948d62 100644 --- a/allianceauth/services/modules/openfire/tasks.py +++ b/allianceauth/services/modules/openfire/tasks.py @@ -19,7 +19,7 @@ class OpenfireTasks: @classmethod def delete_user(cls, user, notify_user=False): if cls.has_account(user): - logger.debug("User %s has jabber account %s. Deleting." % (user, user.openfire.username)) + logger.debug(f"User {user} has jabber account {user.openfire.username}. Deleting.") OpenfireManager.delete_user(user.openfire.username) user.openfire.delete() if notify_user: @@ -48,7 +48,7 @@ class OpenfireTasks: groups = [user.profile.state.name] for group in user.groups.all(): groups.append(str(group.name)) - logger.debug("Updating user %s jabber groups to %s" % (user, groups)) + logger.debug(f"Updating user {user} jabber groups to {groups}") try: OpenfireManager.update_user_groups(user.openfire.username, groups) except: diff --git a/allianceauth/services/modules/openfire/tests.py b/allianceauth/services/modules/openfire/tests.py index a2c50a85..ed1c3fe3 100644 --- a/allianceauth/services/modules/openfire/tests.py +++ b/allianceauth/services/modules/openfire/tests.py @@ -195,7 +195,7 @@ class OpenfireManagerTestCase(TestCase): password = self.manager._OpenfireManager__generate_random_pass() self.assertEqual(len(password), 16) - self.assertIsInstance(password, type('')) + self.assertIsInstance(password, str) def test__sanitize_username(self): test_username = " My_Test User\"'&/:<>@name\\20name" diff --git a/allianceauth/services/modules/openfire/views.py b/allianceauth/services/modules/openfire/views.py index d1a7232d..b24f94f9 100644 --- a/allianceauth/services/modules/openfire/views.py +++ b/allianceauth/services/modules/openfire/views.py @@ -24,7 +24,7 @@ ACCESS_PERM = 'openfire.access_openfire' def activate_jabber(request): logger.debug("activate_jabber called by user %s" % request.user) character = request.user.profile.main_character - logger.debug("Adding jabber user for user %s with main character %s" % (request.user, character)) + logger.debug(f"Adding jabber user for user {request.user} with main character {character}") info = OpenfireManager.add_user(OpenfireTasks.get_username(request.user)) # If our username is blank means we already had a user if info[0] != "": @@ -95,7 +95,7 @@ def jabber_broadcast_view(request): logger.debug("Received POST request containing form, valid: %s" % form.is_valid()) if form.is_valid(): main_char = request.user.profile.main_character - logger.debug("Processing jabber broadcast for user %s with main character %s" % (request.user, main_char)) + logger.debug(f"Processing jabber broadcast for user {request.user} with main character {main_char}") try: if main_char is not None: message_to_send = form.cleaned_data['message'] + "\n##### SENT BY: " + "[" + main_char.corporation_ticker + "]" + \ @@ -120,7 +120,7 @@ def jabber_broadcast_view(request): else: form = JabberBroadcastForm() form.fields['group'].choices = allchoices - logger.debug("Generated broadcast form for user %s containing %s groups" % ( + logger.debug("Generated broadcast form for user {} containing {} groups".format( request.user, len(form.fields['group'].choices))) context = {'form': form} diff --git a/allianceauth/services/modules/phpbb3/auth_hooks.py b/allianceauth/services/modules/phpbb3/auth_hooks.py index 3f09c7d4..9b45694e 100644 --- a/allianceauth/services/modules/phpbb3/auth_hooks.py +++ b/allianceauth/services/modules/phpbb3/auth_hooks.py @@ -25,16 +25,16 @@ class Phpbb3Service(ServicesHook): return 'phpBB3 Forum' def delete_user(self, user, notify_user=False): - logger.debug('Deleting user %s %s account' % (user, self.name)) + logger.debug(f'Deleting user {user} {self.name} account') return Phpbb3Tasks.delete_user(user, notify_user=notify_user) def validate_user(self, user): - logger.debug('Validating user %s %s account' % (user, self.name)) + logger.debug(f'Validating user {user} {self.name} account') if Phpbb3Tasks.has_account(user) and not self.service_active_for_user(user): self.delete_user(user, notify_user=True) def update_groups(self, user): - logger.debug('Updating %s groups for %s' % (self.name, user)) + logger.debug(f'Updating {self.name} groups for {user}') if Phpbb3Tasks.has_account(user): Phpbb3Tasks.update_groups.delay(user.pk) diff --git a/allianceauth/services/modules/phpbb3/manager.py b/allianceauth/services/modules/phpbb3/manager.py index 895f33f9..c62417b1 100755 --- a/allianceauth/services/modules/phpbb3/manager.py +++ b/allianceauth/services/modules/phpbb3/manager.py @@ -58,7 +58,7 @@ class Phpbb3Manager: @staticmethod def __add_avatar(username, characterid): - logger.debug("Adding EVE character id %s portrait as phpbb avater for user %s" % (characterid, username)) + logger.debug(f"Adding EVE character id {characterid} portrait as phpbb avater for user {username}") avatar_url = EveCharacter.generic_portrait_url(characterid, 64) cursor = connections['phpbb3'].cursor() userid = Phpbb3Manager.__get_user_id(username) @@ -81,7 +81,7 @@ class Phpbb3Manager: @staticmethod def _sanitize_groupname(name): name = name.strip(' _') - return re.sub('[^\w.-]', '', name) + return re.sub(r'[^\w.-]', '', name) @staticmethod def __get_group_id(groupname): @@ -89,7 +89,7 @@ class Phpbb3Manager: cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_GET_GROUP_ID, [groupname]) row = cursor.fetchone() - logger.debug("Got phpbb group id %s for groupname %s" % (row[0], groupname)) + logger.debug(f"Got phpbb group id {row[0]} for groupname {groupname}") return row[0] @staticmethod @@ -99,7 +99,7 @@ class Phpbb3Manager: cursor.execute(Phpbb3Manager.SQL_USER_ID_FROM_USERNAME, [username]) row = cursor.fetchone() if row is not None: - logger.debug("Got phpbb user id %s for username %s" % (row[0], username)) + logger.debug(f"Got phpbb user id {row[0]} for username {username}") return row[0] else: logger.error("Username %s not found on phpbb. Unable to determine user id." % username) @@ -123,7 +123,7 @@ class Phpbb3Manager: cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_GET_USER_GROUPS, [userid]) out = [row[0] for row in cursor.fetchall()] - logger.debug("Got user %s phpbb groups %s" % (userid, out)) + logger.debug(f"Got user {userid} phpbb groups {out}") return out @staticmethod @@ -142,38 +142,38 @@ class Phpbb3Manager: @staticmethod def __add_user_to_group(userid, groupid): - logger.debug("Adding phpbb3 user id %s to group id %s" % (userid, groupid)) + logger.debug(f"Adding phpbb3 user id {userid} to group id {groupid}") try: cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_ADD_USER_GROUP, [groupid, userid, 0]) cursor.execute(Phpbb3Manager.SQL_CLEAR_USER_PERMISSIONS, [userid]) - logger.info("Added phpbb user id %s to group id %s" % (userid, groupid)) + logger.info(f"Added phpbb user id {userid} to group id {groupid}") except: - logger.exception("Unable to add phpbb user id %s to group id %s" % (userid, groupid)) + logger.exception(f"Unable to add phpbb user id {userid} to group id {groupid}") pass @staticmethod def __remove_user_from_group(userid, groupid): - logger.debug("Removing phpbb3 user id %s from group id %s" % (userid, groupid)) + logger.debug(f"Removing phpbb3 user id {userid} from group id {groupid}") try: cursor = connections['phpbb3'].cursor() cursor.execute(Phpbb3Manager.SQL_REMOVE_USER_GROUP, [userid, groupid]) cursor.execute(Phpbb3Manager.SQL_CLEAR_USER_PERMISSIONS, [userid]) - logger.info("Removed phpbb user id %s from group id %s" % (userid, groupid)) + logger.info(f"Removed phpbb user id {userid} from group id {groupid}") except: - logger.exception("Unable to remove phpbb user id %s from group id %s" % (userid, groupid)) + logger.exception(f"Unable to remove phpbb user id {userid} from group id {groupid}") pass @staticmethod def add_user(username, email, groups, characterid): - logger.debug("Adding phpbb user with username %s, email %s, groups %s, characterid %s" % ( + logger.debug("Adding phpbb user with username {}, email {}, groups {}, characterid {}".format( username, email, groups, characterid)) cursor = connections['phpbb3'].cursor() username_clean = Phpbb3Manager.__santatize_username(username) password = Phpbb3Manager.__generate_random_pass() pwhash = Phpbb3Manager.__gen_hash(password) - logger.debug("Proceeding to add phpbb user %s and pwhash starting with %s" % (username_clean, pwhash[0:5])) + logger.debug(f"Proceeding to add phpbb user {username_clean} and pwhash starting with {pwhash[0:5]}") # check if the username was simply revoked if Phpbb3Manager.check_user(username_clean): logger.warn("Unable to add phpbb user with username %s - already exists. Updating user instead." % username) @@ -228,14 +228,14 @@ class Phpbb3Manager: @staticmethod def update_groups(username, groups): userid = Phpbb3Manager.__get_user_id(username) - logger.debug("Updating phpbb user %s with id %s groups %s" % (username, userid, groups)) + logger.debug(f"Updating phpbb user {username} with id {userid} groups {groups}") if userid is not None: forum_groups = Phpbb3Manager.__get_all_groups() user_groups = set(Phpbb3Manager.__get_user_groups(userid)) - act_groups = set([Phpbb3Manager._sanitize_groupname(g) for g in groups]) + act_groups = {Phpbb3Manager._sanitize_groupname(g) for g in groups} addgroups = act_groups - user_groups remgroups = user_groups - act_groups - logger.info("Updating phpbb user %s groups - adding %s, removing %s" % (username, addgroups, remgroups)) + logger.info(f"Updating phpbb user {username} groups - adding {addgroups}, removing {remgroups}") for g in addgroups: if not g in forum_groups: forum_groups[g] = Phpbb3Manager.__create_group(g) @@ -246,7 +246,7 @@ class Phpbb3Manager: @staticmethod def remove_group(username, group): - logger.debug("Removing phpbb user %s from group %s" % (username, group)) + logger.debug(f"Removing phpbb user {username} from group {group}") cursor = connections['phpbb3'].cursor() userid = Phpbb3Manager.__get_user_id(username) if userid is not None: @@ -256,10 +256,10 @@ class Phpbb3Manager: if groupid: try: cursor.execute(Phpbb3Manager.SQL_REMOVE_USER_GROUP, [userid, groupid]) - logger.info("Removed phpbb user %s from group %s" % (username, group)) + logger.info(f"Removed phpbb user {username} from group {group}") except: logger.exception( - "Exception prevented removal of phpbb user %s with id %s from group %s with id %s" % ( + "Exception prevented removal of phpbb user {} with id {} from group {} with id {}".format( username, userid, group, groupid)) pass @@ -284,7 +284,7 @@ class Phpbb3Manager: if Phpbb3Manager.check_user(username): pwhash = Phpbb3Manager.__gen_hash(password) logger.debug( - "Proceeding to update phpbb user %s password with pwhash starting with %s" % (username, pwhash[0:5])) + f"Proceeding to update phpbb user {username} password with pwhash starting with {pwhash[0:5]}") cursor.execute(Phpbb3Manager.SQL_UPDATE_USER_PASSWORD, [pwhash, username]) Phpbb3Manager.__add_avatar(username, characterid) logger.info("Updated phpbb user %s password." % username) @@ -295,7 +295,7 @@ class Phpbb3Manager: @staticmethod def __update_user_info(username, email, password): logger.debug( - "Updating phpbb user %s info: username %s password of length %s" % (username, email, len(password))) + f"Updating phpbb user {username} info: username {email} password of length {len(password)}") cursor = connections['phpbb3'].cursor() try: cursor.execute(Phpbb3Manager.SQL_DIS_USER, [email, password, username]) diff --git a/allianceauth/services/modules/phpbb3/migrations/0001_initial.py b/allianceauth/services/modules/phpbb3/migrations/0001_initial.py index db3ec534..151aa380 100644 --- a/allianceauth/services/modules/phpbb3/migrations/0001_initial.py +++ b/allianceauth/services/modules/phpbb3/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:28 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/phpbb3/migrations/0002_service_permissions.py b/allianceauth/services/modules/phpbb3/migrations/0002_service_permissions.py index 656210c3..6757c2df 100644 --- a/allianceauth/services/modules/phpbb3/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/phpbb3/migrations/0002_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_phpbb3') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if Phpbb3User.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_FORUM'), False): + getattr(settings, 'ENABLE_AUTH_FORUM', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if Phpbb3User.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_FORUM'), False): + getattr(settings, 'ENABLE_BLUE_FORUM', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/phpbb3/models.py b/allianceauth/services/modules/phpbb3/models.py index a2de5917..a283d4b4 100644 --- a/allianceauth/services/modules/phpbb3/models.py +++ b/allianceauth/services/modules/phpbb3/models.py @@ -13,5 +13,5 @@ class Phpbb3User(models.Model): class Meta: permissions = ( - ("access_phpbb3", u"Can access the phpBB3 service"), + ("access_phpbb3", "Can access the phpBB3 service"), ) diff --git a/allianceauth/services/modules/phpbb3/tasks.py b/allianceauth/services/modules/phpbb3/tasks.py index 6c9b7503..53cf1331 100644 --- a/allianceauth/services/modules/phpbb3/tasks.py +++ b/allianceauth/services/modules/phpbb3/tasks.py @@ -19,7 +19,7 @@ class Phpbb3Tasks: @classmethod def delete_user(cls, user, notify_user=False): if cls.has_account(user): - logger.debug("User %s has forum account %s. Deleting." % (user, user.phpbb3.username)) + logger.debug(f"User {user} has forum account {user.phpbb3.username}. Deleting.") if Phpbb3Manager.disable_user(user.phpbb3.username): user.phpbb3.delete() if notify_user: @@ -43,7 +43,7 @@ class Phpbb3Tasks: groups = [user.profile.state.name] for group in user.groups.all(): groups.append(str(group.name)) - logger.debug("Updating user %s phpbb3 groups to %s" % (user, groups)) + logger.debug(f"Updating user {user} phpbb3 groups to {groups}") try: Phpbb3Manager.update_groups(user.phpbb3.username, groups) except: diff --git a/allianceauth/services/modules/phpbb3/tests.py b/allianceauth/services/modules/phpbb3/tests.py index cd5de997..f6d250bf 100644 --- a/allianceauth/services/modules/phpbb3/tests.py +++ b/allianceauth/services/modules/phpbb3/tests.py @@ -195,7 +195,7 @@ class Phpbb3ManagerTestCase(TestCase): password = self.manager._Phpbb3Manager__generate_random_pass() self.assertEqual(len(password), 16) - self.assertIsInstance(password, type('')) + self.assertIsInstance(password, str) def test_gen_pwhash(self): pwhash = self.manager._Phpbb3Manager__gen_hash('test') diff --git a/allianceauth/services/modules/phpbb3/views.py b/allianceauth/services/modules/phpbb3/views.py index d5a19bd8..b847c8af 100644 --- a/allianceauth/services/modules/phpbb3/views.py +++ b/allianceauth/services/modules/phpbb3/views.py @@ -22,7 +22,7 @@ def activate_forum(request): logger.debug("activate_forum called by user %s" % request.user) # Valid now we get the main characters character = request.user.profile.main_character - logger.debug("Adding phpbb user for user %s with main character %s" % (request.user, character)) + logger.debug(f"Adding phpbb user for user {request.user} with main character {character}") result = Phpbb3Manager.add_user(Phpbb3Tasks.get_username(request.user), request.user.email, ['REGISTERED'], character.character_id) # if empty we failed diff --git a/allianceauth/services/modules/smf/auth_hooks.py b/allianceauth/services/modules/smf/auth_hooks.py index 9baa3136..d2c9618d 100644 --- a/allianceauth/services/modules/smf/auth_hooks.py +++ b/allianceauth/services/modules/smf/auth_hooks.py @@ -25,16 +25,16 @@ class SmfService(ServicesHook): return 'SMF Forums' def delete_user(self, user, notify_user=False): - logger.debug('Deleting user %s %s account' % (user, self.name)) + logger.debug(f'Deleting user {user} {self.name} account') return SmfTasks.delete_user(user, notify_user=notify_user) def validate_user(self, user): - logger.debug('Validating user %s %s account' % (user, self.name)) + logger.debug(f'Validating user {user} {self.name} account') if SmfTasks.has_account(user) and not self.service_active_for_user(user): self.delete_user(user) def update_groups(self, user): - logger.debug('Updating %s groups for %s' % (self.name, user)) + logger.debug(f'Updating {self.name} groups for {user}') if SmfTasks.has_account(user): SmfTasks.update_groups.delay(user.pk) diff --git a/allianceauth/services/modules/smf/manager.py b/allianceauth/services/modules/smf/manager.py index 1a7d8893..e4f52569 100644 --- a/allianceauth/services/modules/smf/manager.py +++ b/allianceauth/services/modules/smf/manager.py @@ -49,7 +49,7 @@ class SmfManager: @staticmethod def _sanitize_groupname(name): name = name.strip(' _') - return re.sub('[^\w.-]', '', name) + return re.sub(r'[^\w.-]', '', name) @staticmethod def generate_random_pass(): @@ -85,7 +85,7 @@ class SmfManager: cursor = connections['smf'].cursor() cursor.execute(cls.SQL_GET_GROUP_ID, [groupname]) row = cursor.fetchone() - logger.debug("Got smf group id %s for groupname %s" % (row[0], groupname)) + logger.debug(f"Got smf group id {row[0]} for groupname {groupname}") return row[0] @classmethod @@ -102,7 +102,7 @@ class SmfManager: @classmethod def add_avatar(cls, member_name, characterid): - logger.debug("Adding EVE character id %s portrait as smf avatar for user %s" % (characterid, member_name)) + logger.debug(f"Adding EVE character id {characterid} portrait as smf avatar for user {member_name}") avatar_url = EveCharacter.generic_portrait_url(characterid, 64) cursor = connections['smf'].cursor() id_member = cls.get_user_id(member_name) @@ -115,7 +115,7 @@ class SmfManager: cursor.execute(cls.SQL_USER_ID_FROM_USERNAME, [username]) row = cursor.fetchone() if row is not None: - logger.debug("Got smf user id %s for username %s" % (row[0], username)) + logger.debug(f"Got smf user id {row[0]} for username {username}") return row[0] else: logger.error("username %s not found on smf. Unable to determine user id ." % username) @@ -139,18 +139,18 @@ class SmfManager: cursor = connections['smf'].cursor() cursor.execute(cls.SQL_GET_USER_GROUPS, [userid]) out = [row[0] for row in cursor.fetchall()] - logger.debug("Got user %s smf groups %s" % (userid, out)) + logger.debug(f"Got user {userid} smf groups {out}") return out @classmethod def add_user(cls, username, email_address, groups, characterid): - logger.debug("Adding smf user with member_name %s, email_address %s, characterid %s" % ( + logger.debug("Adding smf user with member_name {}, email_address {}, characterid {}".format( username, email_address, characterid)) cursor = connections['smf'].cursor() username_clean = cls.santatize_username(username) passwd = cls.generate_random_pass() pwhash = cls.gen_hash(username_clean, passwd) - logger.debug("Proceeding to add smf user %s and pwhash starting with %s" % (username, pwhash[0:5])) + logger.debug(f"Proceeding to add smf user {username} and pwhash starting with {pwhash[0:5]}") register_date = cls.get_current_utc_date() # check if the username was simply revoked if cls.check_user(username) is True: @@ -171,7 +171,7 @@ class SmfManager: @classmethod def __update_user_info(cls, username, email_address, passwd): logger.debug( - "Updating smf user %s info: username %s password of length %s" % (username, email_address, len(passwd))) + f"Updating smf user {username} info: username {email_address} password of length {len(passwd)}") cursor = connections['smf'].cursor() try: cursor.execute(cls.SQL_DIS_USER, [email_address, passwd, username]) @@ -195,14 +195,14 @@ class SmfManager: @classmethod def update_groups(cls, username, groups): userid = cls.get_user_id(username) - logger.debug("Updating smf user %s with id %s groups %s" % (username, userid, groups)) + logger.debug(f"Updating smf user {username} with id {userid} groups {groups}") if userid is not None: forum_groups = cls.get_all_groups() user_groups = set(cls.get_user_groups(userid)) - act_groups = set([cls._sanitize_groupname(g) for g in groups]) + act_groups = {cls._sanitize_groupname(g) for g in groups} addgroups = act_groups - user_groups remgroups = user_groups - act_groups - logger.info("Updating smf user %s groups - adding %s, removing %s" % (username, addgroups, remgroups)) + logger.info(f"Updating smf user {username} groups - adding {addgroups}, removing {remgroups}") act_group_id = set() for g in addgroups: if g not in forum_groups: @@ -213,24 +213,24 @@ class SmfManager: @classmethod def add_user_to_group(cls, userid, groupid): - logger.debug("Adding smf user id %s to group id %s" % (userid, groupid)) + logger.debug(f"Adding smf user id {userid} to group id {groupid}") try: cursor = connections['smf'].cursor() cursor.execute(cls.SQL_ADD_USER_GROUP, [groupid, userid]) - logger.info("Added smf user id %s to group id %s" % (userid, groupid)) + logger.info(f"Added smf user id {userid} to group id {groupid}") except: - logger.exception("Unable to add smf user id %s to group id %s" % (userid, groupid)) + logger.exception(f"Unable to add smf user id {userid} to group id {groupid}") pass @classmethod def remove_user_from_group(cls, userid, groupid): - logger.debug("Removing smf user id %s from group id %s" % (userid, groupid)) + logger.debug(f"Removing smf user id {userid} from group id {groupid}") try: cursor = connections['smf'].cursor() cursor.execute(cls.SQL_REMOVE_USER_GROUP, [groupid, userid]) - logger.info("Removed smf user id %s from group id %s" % (userid, groupid)) + logger.info(f"Removed smf user id {userid} from group id {groupid}") except: - logger.exception("Unable to remove smf user id %s from group id %s" % (userid, groupid)) + logger.exception(f"Unable to remove smf user id {userid} from group id {groupid}") pass @classmethod @@ -261,7 +261,7 @@ class SmfManager: username_clean = cls.santatize_username(username) pwhash = cls.gen_hash(username_clean, password) logger.debug( - "Proceeding to update smf user %s password with pwhash starting with %s" % (username, pwhash[0:5])) + f"Proceeding to update smf user {username} password with pwhash starting with {pwhash[0:5]}") cursor.execute(cls.SQL_UPDATE_USER_PASSWORD, [pwhash, username]) cls.add_avatar(username, characterid) logger.info("Updated smf user %s password." % username) diff --git a/allianceauth/services/modules/smf/migrations/0001_initial.py b/allianceauth/services/modules/smf/migrations/0001_initial.py index d8da235c..b4ce2f34 100644 --- a/allianceauth/services/modules/smf/migrations/0001_initial.py +++ b/allianceauth/services/modules/smf/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:28 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/smf/migrations/0002_service_permissions.py b/allianceauth/services/modules/smf/migrations/0002_service_permissions.py index fdf93adb..611111eb 100644 --- a/allianceauth/services/modules/smf/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/smf/migrations/0002_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_smf') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if SmfUser.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_SMF'), False): + getattr(settings, 'ENABLE_AUTH_SMF', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if SmfUser.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_SMF'), False): + getattr(settings, 'ENABLE_BLUE_SMF', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/smf/models.py b/allianceauth/services/modules/smf/models.py index 381cd44f..4e44821d 100644 --- a/allianceauth/services/modules/smf/models.py +++ b/allianceauth/services/modules/smf/models.py @@ -13,5 +13,5 @@ class SmfUser(models.Model): class Meta: permissions = ( - ("access_smf", u"Can access the SMF service"), + ("access_smf", "Can access the SMF service"), ) diff --git a/allianceauth/services/modules/smf/tasks.py b/allianceauth/services/modules/smf/tasks.py index 847fb52c..580c8e86 100644 --- a/allianceauth/services/modules/smf/tasks.py +++ b/allianceauth/services/modules/smf/tasks.py @@ -19,7 +19,7 @@ class SmfTasks: @classmethod def delete_user(cls, user, notify_user=False): if cls.has_account(user): - logger.debug("User %s has a SMF account %s. Deleting." % (user, user.smf.username)) + logger.debug(f"User {user} has a SMF account {user.smf.username}. Deleting.") SmfManager.disable_user(user.smf.username) user.smf.delete() if notify_user: @@ -47,7 +47,7 @@ class SmfTasks: groups = [user.profile.state.name] for group in user.groups.all(): groups.append(str(group.name)) - logger.debug("Updating user %s smf groups to %s" % (user, groups)) + logger.debug(f"Updating user {user} smf groups to {groups}") try: SmfManager.update_groups(user.smf.username, groups) except: diff --git a/allianceauth/services/modules/smf/tests.py b/allianceauth/services/modules/smf/tests.py index ed58e818..b6c20895 100644 --- a/allianceauth/services/modules/smf/tests.py +++ b/allianceauth/services/modules/smf/tests.py @@ -195,7 +195,7 @@ class SmfManagerTestCase(TestCase): password = self.manager.generate_random_pass() self.assertEqual(len(password), 16) - self.assertIsInstance(password, type('')) + self.assertIsInstance(password, str) def test_gen_hash(self): pwhash = self.manager.gen_hash('username', 'test') diff --git a/allianceauth/services/modules/smf/views.py b/allianceauth/services/modules/smf/views.py index b8dbe688..b7d26635 100644 --- a/allianceauth/services/modules/smf/views.py +++ b/allianceauth/services/modules/smf/views.py @@ -22,7 +22,7 @@ def activate_smf(request): logger.debug("activate_smf called by user %s" % request.user) # Valid now we get the main characters character = request.user.profile.main_character - logger.debug("Adding smf user for user %s with main character %s" % (request.user, character)) + logger.debug(f"Adding smf user for user {request.user} with main character {character}") result = SmfManager.add_user(SmfTasks.get_username(request.user), request.user.email, ['Member'], character.character_id) # if empty we failed if result[0] != "": diff --git a/allianceauth/services/modules/teamspeak3/auth_hooks.py b/allianceauth/services/modules/teamspeak3/auth_hooks.py index f4ef6af1..20e82326 100644 --- a/allianceauth/services/modules/teamspeak3/auth_hooks.py +++ b/allianceauth/services/modules/teamspeak3/auth_hooks.py @@ -21,15 +21,15 @@ class Teamspeak3Service(ServicesHook): self.name_format = '[{corp_ticker}]{character_name}' def delete_user(self, user, notify_user=False): - logger.debug('Deleting user %s %s account' % (user, self.name)) + logger.debug(f'Deleting user {user} {self.name} account') return Teamspeak3Tasks.delete_user(user, notify_user=notify_user) def update_groups(self, user): - logger.debug('Updating %s groups for %s' % (self.name, user)) + logger.debug(f'Updating {self.name} groups for {user}') Teamspeak3Tasks.update_groups.delay(user.pk) def validate_user(self, user): - logger.debug('Validating user %s %s account' % (user, self.name)) + logger.debug(f'Validating user {user} {self.name} account') if Teamspeak3Tasks.has_account(user) and not self.service_active_for_user(user): self.delete_user(user, notify_user=True) diff --git a/allianceauth/services/modules/teamspeak3/manager.py b/allianceauth/services/modules/teamspeak3/manager.py index 7074a34f..d05f910d 100755 --- a/allianceauth/services/modules/teamspeak3/manager.py +++ b/allianceauth/services/modules/teamspeak3/manager.py @@ -55,7 +55,7 @@ class Teamspeak3Manager: try: ret = self.server.send_command('customsearch', {'ident': 'sso_uid', 'pattern': uid}) if ret and 'keys' in ret and 'cldbid' in ret['keys']: - logger.debug("Got userid %s for uid %s" % (ret['keys']['cldbid'], uid)) + logger.debug("Got userid {} for uid {}".format(ret['keys']['cldbid'], uid)) return ret['keys']['cldbid'] except TeamspeakError as e: if not e.code == '1281': @@ -71,7 +71,7 @@ class Teamspeak3Manager: continue logger.debug("Checking group %s" % group) if group['keys']['name'] == groupname: - logger.debug("Found group %s, returning id %s" % (groupname, group['keys']['sgid'])) + logger.debug("Found group {}, returning id {}".format(groupname, group['keys']['sgid'])) return group['keys']['sgid'] logger.debug("Group %s not found on server." % groupname) return None @@ -93,7 +93,7 @@ class Teamspeak3Manager: self.server.send_command('servergroupaddperm', {'sgid': sgid, 'permsid': 'i_group_needed_member_remove_power', 'permvalue': 100, 'permnegated': 0, 'permskip': 0}) - logger.info("Created group on TS3 server with name %s and id %s" % (groupname, sgid)) + logger.info(f"Created group on TS3 server with name {groupname} and id {sgid}") return sgid def _user_group_list(self, cldbid): @@ -128,7 +128,7 @@ class Teamspeak3Manager: for group in group_cache: if group['keys']['type'] != '1': continue - logger.debug("Assigning name/id dict: %s = %s" % (group['keys']['name'], group['keys']['sgid'])) + logger.debug("Assigning name/id dict: {} = {}".format(group['keys']['name'], group['keys']['sgid'])) outlist[group['keys']['name']] = group['keys']['sgid'] else: logger.error("Received empty group cache while retrieving group cache from TS3 server. 1024 error.") @@ -136,24 +136,24 @@ class Teamspeak3Manager: return outlist def _add_user_to_group(self, uid, groupid): - logger.debug("Adding group id %s to TS3 user id %s" % (groupid, uid)) + logger.debug(f"Adding group id {groupid} to TS3 user id {uid}") user_groups = self._user_group_list(uid) if groupid not in user_groups.values(): logger.debug("User does not have group already. Issuing command to add.") self.server.send_command('servergroupaddclient', {'sgid': str(groupid), 'cldbid': uid}) - logger.info("Added user id %s to group id %s on TS3 server." % (uid, groupid)) + logger.info(f"Added user id {uid} to group id {groupid} on TS3 server.") def _remove_user_from_group(self, uid, groupid): - logger.debug("Removing group id %s from TS3 user id %s" % (groupid, uid)) + logger.debug(f"Removing group id {groupid} from TS3 user id {uid}") user_groups = self._user_group_list(uid) if str(groupid) in user_groups.values(): logger.debug("User is in group. Issuing command to remove.") self.server.send_command('servergroupdelclient', {'sgid': str(groupid), 'cldbid': uid}) - logger.info("Removed user id %s from group id %s on TS3 server." % (uid, groupid)) + logger.info(f"Removed user id {uid} from group id {groupid} on TS3 server.") def _sync_ts_group_db(self): logger.debug("_sync_ts_group_db function called.") @@ -162,20 +162,20 @@ class Teamspeak3Manager: local_groups = TSgroup.objects.all() logger.debug("Comparing remote groups to TSgroup objects: %s" % local_groups) for key in remote_groups: - logger.debug("Typecasting remote_group value at position %s to int: %s" % (key, remote_groups[key])) + logger.debug(f"Typecasting remote_group value at position {key} to int: {remote_groups[key]}") remote_groups[key] = int(remote_groups[key]) for group in local_groups: logger.debug("Checking local group %s" % group) if group.ts_group_id not in remote_groups.values(): logger.debug( - "Local group id %s not found on server. Deleting model %s" % (group.ts_group_id, group)) + f"Local group id {group.ts_group_id} not found on server. Deleting model {group}") TSgroup.objects.filter(ts_group_id=group.ts_group_id).delete() for key in remote_groups: g = TSgroup(ts_group_id=remote_groups[key], ts_group_name=key) q = TSgroup.objects.filter(ts_group_id=g.ts_group_id) if not q: - logger.debug("Local group does not exist for TS group %s. Creating TSgroup model %s" % ( + logger.debug("Local group does not exist for TS group {}. Creating TSgroup model {}".format( remote_groups[key], g)) g.save() except TeamspeakError as e: @@ -199,7 +199,7 @@ class Teamspeak3Manager: 'tokendescription': username_clean, 'tokencustomset': "ident=sso_uid value=%s" % username_clean}) except TeamspeakError as e: - logger.error("Failed to add teamspeak user %s: %s" % (username_clean, str(e))) + logger.error(f"Failed to add teamspeak user {username_clean}: {str(e)}") return "","" try: @@ -207,12 +207,12 @@ class Teamspeak3Manager: logger.info("Created permission token for user %s on TS3 server" % username_clean) return username_clean, token except: - logger.exception("Failed to add teamspeak user %s - received response: %s" % (username_clean, ret)) + logger.exception(f"Failed to add teamspeak user {username_clean} - received response: {ret}") return "", "" def delete_user(self, uid): user = self._get_userid(uid) - logger.debug("Deleting user %s with id %s from TS3 server." % (user, uid)) + logger.debug(f"Deleting user {user} with id {uid} from TS3 server.") if user: clients = self.server.send_command('clientlist') if isinstance(clients, dict): @@ -226,18 +226,18 @@ class Teamspeak3Manager: self.server.send_command('clientkick', {'clid': client['keys']['clid'], 'reasonid': 5, 'reasonmsg': 'Auth service deleted'}) except: - logger.exception("Failed to delete user id %s from TS3 - received response %s" % (uid, client)) + logger.exception(f"Failed to delete user id {uid} from TS3 - received response {client}") return False try: ret = self.server.send_command('clientdbdelete', {'cldbid': user}) except TeamspeakError as e: - logger.error("Failed to delete teamspeak user %s: %s" % (uid, str(e))) + logger.error(f"Failed to delete teamspeak user {uid}: {str(e)}") return False if ret == '0': logger.info("Deleted user with id %s from TS3 server." % uid) return True else: - logger.exception("Failed to delete user id %s from TS3 - received response %s" % (uid, ret)) + logger.exception(f"Failed to delete user id {uid} from TS3 - received response {ret}") return False else: logger.warn("User with id %s not found on TS3 server. Assuming succesful deletion." % uid) @@ -255,7 +255,7 @@ class Teamspeak3Manager: return self.add_user(user, username) def update_groups(self, uid, ts_groups): - logger.debug("Updating uid %s TS3 groups %s" % (uid, ts_groups)) + logger.debug(f"Updating uid {uid} TS3 groups {ts_groups}") userid = self._get_userid(uid) addgroups = [] remgroups = [] @@ -273,9 +273,9 @@ class Teamspeak3Manager: remgroups.append(user_ts_groups[user_ts_group_key]) for g in addgroups: - logger.info("Adding Teamspeak user %s into group %s" % (userid, g)) + logger.info(f"Adding Teamspeak user {userid} into group {g}") self._add_user_to_group(userid, g) for g in remgroups: - logger.info("Removing Teamspeak user %s from group %s" % (userid, g)) + logger.info(f"Removing Teamspeak user {userid} from group {g}") self._remove_user_from_group(userid, g) diff --git a/allianceauth/services/modules/teamspeak3/migrations/0001_initial.py b/allianceauth/services/modules/teamspeak3/migrations/0001_initial.py index 2177f500..3f22e872 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0001_initial.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 01:11 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/teamspeak3/migrations/0002_auto_20161212_0133.py b/allianceauth/services/modules/teamspeak3/migrations/0002_auto_20161212_0133.py index c7c8b076..cf71c33c 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0002_auto_20161212_0133.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0002_auto_20161212_0133.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 01:33 -from __future__ import unicode_literals from django.db import migrations diff --git a/allianceauth/services/modules/teamspeak3/migrations/0003_teamspeak3user.py b/allianceauth/services/modules/teamspeak3/migrations/0003_teamspeak3user.py index 6eea5c83..dbe71b6c 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0003_teamspeak3user.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0003_teamspeak3user.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:14 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/teamspeak3/migrations/0004_service_permissions.py b/allianceauth/services/modules/teamspeak3/migrations/0004_service_permissions.py index 43e00fa4..4023cbff 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0004_service_permissions.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0004_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_teamspeak3') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if Teamspeak3User.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_TEAMSPEAK3'), False): + getattr(settings, 'ENABLE_AUTH_TEAMSPEAK3', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if Teamspeak3User.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_TEAMSPEAK3'), False): + getattr(settings, 'ENABLE_BLUE_TEAMSPEAK3', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/teamspeak3/migrations/0005_stategroup.py b/allianceauth/services/modules/teamspeak3/migrations/0005_stategroup.py index 8b77d8fc..0cd994eb 100644 --- a/allianceauth/services/modules/teamspeak3/migrations/0005_stategroup.py +++ b/allianceauth/services/modules/teamspeak3/migrations/0005_stategroup.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.10 on 2018-02-23 06:13 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/services/modules/teamspeak3/models.py b/allianceauth/services/modules/teamspeak3/models.py index 86f60f0f..5569a35c 100644 --- a/allianceauth/services/modules/teamspeak3/models.py +++ b/allianceauth/services/modules/teamspeak3/models.py @@ -16,7 +16,7 @@ class Teamspeak3User(models.Model): class Meta: permissions = ( - ("access_teamspeak3", u"Can access the Teamspeak3 service"), + ("access_teamspeak3", "Can access the Teamspeak3 service"), ) diff --git a/allianceauth/services/modules/teamspeak3/signals.py b/allianceauth/services/modules/teamspeak3/signals.py index 6ae97778..59054d10 100644 --- a/allianceauth/services/modules/teamspeak3/signals.py +++ b/allianceauth/services/modules/teamspeak3/signals.py @@ -19,7 +19,7 @@ def trigger_all_ts_update(): @receiver(m2m_changed, sender=AuthTS.ts_group.through) def m2m_changed_authts_group(sender, instance, action, *args, **kwargs): - logger.debug("Received m2m_changed from %s ts_group with action %s" % (instance, action)) + logger.debug(f"Received m2m_changed from {instance} ts_group with action {action}") if action == "post_add" or action == "post_remove": transaction.on_commit(trigger_all_ts_update) @@ -45,5 +45,5 @@ post_delete.connect(post_delete_authts, sender=StateGroup) def check_groups_on_state_change(sender, user, state, **kwargs): def trigger_update(): Teamspeak3Tasks.update_groups.delay(user.pk) - logger.debug("Received state_changed signal from {}".format(user)) + logger.debug(f"Received state_changed signal from {user}") transaction.on_commit(trigger_update) diff --git a/allianceauth/services/modules/teamspeak3/tasks.py b/allianceauth/services/modules/teamspeak3/tasks.py index 96779e3b..c65e123d 100644 --- a/allianceauth/services/modules/teamspeak3/tasks.py +++ b/allianceauth/services/modules/teamspeak3/tasks.py @@ -20,7 +20,7 @@ class Teamspeak3Tasks: @classmethod def delete_user(cls, user, notify_user=False): if cls.has_account(user): - logger.debug("User %s has TS3 account %s. Deleting." % (user, user.teamspeak3.uid)) + logger.debug(f"User {user} has TS3 account {user.teamspeak3.uid}. Deleting.") with Teamspeak3Manager() as ts3man: if ts3man.delete_user(user.teamspeak3.uid): user.teamspeak3.delete() @@ -71,13 +71,13 @@ class Teamspeak3Tasks: groups[ts_group.ts_group_name] = ts_group.ts_group_id for stategroup in user.profile.state.stategroup_set.all(): groups[stategroup.ts_group.ts_group_name] = stategroup.ts_group.ts_group_id - logger.debug("Updating user %s teamspeak3 groups to %s" % (user, groups)) + logger.debug(f"Updating user {user} teamspeak3 groups to {groups}") try: with Teamspeak3Manager() as ts3man: ts3man.update_groups(user.teamspeak3.uid, groups) logger.debug("Updated user %s teamspeak3 groups." % user) except TeamspeakError as e: - logger.error("Error occured while syncing TS groups for %s: %s" % (user, str(e))) + logger.error(f"Error occured while syncing TS groups for {user}: {str(e)}") raise self.retry(countdown=60*10) else: logger.debug("User does not have a teamspeak3 account") diff --git a/allianceauth/services/modules/teamspeak3/util/ts3.py b/allianceauth/services/modules/teamspeak3/util/ts3.py index df4a2269..81ae74a6 100755 --- a/allianceauth/services/modules/teamspeak3/util/ts3.py +++ b/allianceauth/services/modules/teamspeak3/util/ts3.py @@ -8,7 +8,7 @@ class ConnectionError: self.port = port def __str__(self): - return 'Error connecting to host %s port %s' % (self.ip, self.port) + return f'Error connecting to host {self.ip} port {self.port}' ts3_escape = { @@ -32,7 +32,7 @@ class TS3Proto: EOL = b'\n\r' def __init__(self): - self._log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__)) + self._log = logging.getLogger(f'{__name__}.{self.__class__.__name__}') self._conn = None self._connected = False @@ -122,10 +122,10 @@ class TS3Proto: if isinstance(keys[key], list): ncstr = [] for nest in keys[key]: - ncstr.append("%s=%s" % (key, self._escape_str(nest))) + ncstr.append(f"{key}={self._escape_str(nest)}") cstr.append("|".join(ncstr)) else: - cstr.append("%s=%s" % (key, self._escape_str(keys[key]))) + cstr.append(f"{key}={self._escape_str(keys[key])}") # Add in options if opts: diff --git a/allianceauth/services/modules/teamspeak3/views.py b/allianceauth/services/modules/teamspeak3/views.py index db87eddc..3d1ff5e2 100644 --- a/allianceauth/services/modules/teamspeak3/views.py +++ b/allianceauth/services/modules/teamspeak3/views.py @@ -24,7 +24,7 @@ def activate_teamspeak3(request): character = request.user.profile.main_character with Teamspeak3Manager() as ts3man: - logger.debug("Adding TS3 user for user %s with main character %s" % (request.user, character)) + logger.debug(f"Adding TS3 user for user {request.user} with main character {character}") result = ts3man.add_user(request.user, Teamspeak3Tasks.get_username(request.user)) # if its empty we failed diff --git a/allianceauth/services/modules/xenforo/auth_hooks.py b/allianceauth/services/modules/xenforo/auth_hooks.py index 3f5d149f..0faa23ac 100644 --- a/allianceauth/services/modules/xenforo/auth_hooks.py +++ b/allianceauth/services/modules/xenforo/auth_hooks.py @@ -23,11 +23,11 @@ class XenforoService(ServicesHook): return 'XenForo Forums' def delete_user(self, user, notify_user=False): - logger.debug('Deleting user %s %s account' % (user, self.name)) + logger.debug(f'Deleting user {user} {self.name} account') return XenforoTasks.delete_user(user, notify_user=notify_user) def validate_user(self, user): - logger.debug('Validating user %s %s account' % (user, self.name)) + logger.debug(f'Validating user {user} {self.name} account') if XenforoTasks.has_account(user) and not self.service_active_for_user(user): self.delete_user(user, notify_user=True) diff --git a/allianceauth/services/modules/xenforo/migrations/0001_initial.py b/allianceauth/services/modules/xenforo/migrations/0001_initial.py index 6c9cd3b2..7bb8dce7 100644 --- a/allianceauth/services/modules/xenforo/migrations/0001_initial.py +++ b/allianceauth/services/modules/xenforo/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.2 on 2016-12-12 03:14 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/services/modules/xenforo/migrations/0002_service_permissions.py b/allianceauth/services/modules/xenforo/migrations/0002_service_permissions.py index 2926f8a6..4bc03a4a 100644 --- a/allianceauth/services/modules/xenforo/migrations/0002_service_permissions.py +++ b/allianceauth/services/modules/xenforo/migrations/0002_service_permissions.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-02-02 05:59 -from __future__ import unicode_literals from django.db import migrations from django.conf import settings @@ -23,12 +22,12 @@ def migrate_service_enabled(apps, schema_editor): perm = Permission.objects.get(codename='access_xenforo') - member_group_name = getattr(settings, str('DEFAULT_AUTH_GROUP'), 'Member') - blue_group_name = getattr(settings, str('DEFAULT_BLUE_GROUP'), 'Blue') + member_group_name = getattr(settings, 'DEFAULT_AUTH_GROUP', 'Member') + blue_group_name = getattr(settings, 'DEFAULT_BLUE_GROUP', 'Blue') # Migrate members if XenforoUser.objects.filter(user__groups__name=member_group_name).exists() or \ - getattr(settings, str('ENABLE_AUTH_XENFORO'), False): + getattr(settings, 'ENABLE_AUTH_XENFORO', False): try: group = Group.objects.get(name=member_group_name) group.permissions.add(perm) @@ -37,7 +36,7 @@ def migrate_service_enabled(apps, schema_editor): # Migrate blues if XenforoUser.objects.filter(user__groups__name=blue_group_name).exists() or \ - getattr(settings, str('ENABLE_BLUE_XENFORO'), False): + getattr(settings, 'ENABLE_BLUE_XENFORO', False): try: group = Group.objects.get(name=blue_group_name) group.permissions.add(perm) diff --git a/allianceauth/services/modules/xenforo/models.py b/allianceauth/services/modules/xenforo/models.py index 80d8bb97..fb326d25 100644 --- a/allianceauth/services/modules/xenforo/models.py +++ b/allianceauth/services/modules/xenforo/models.py @@ -13,5 +13,5 @@ class XenforoUser(models.Model): class Meta: permissions = ( - ("access_xenforo", u"Can access the XenForo service"), + ("access_xenforo", "Can access the XenForo service"), ) diff --git a/allianceauth/services/modules/xenforo/tasks.py b/allianceauth/services/modules/xenforo/tasks.py index 0cb06694..78c7748d 100644 --- a/allianceauth/services/modules/xenforo/tasks.py +++ b/allianceauth/services/modules/xenforo/tasks.py @@ -17,7 +17,7 @@ class XenforoTasks: @classmethod def delete_user(cls, user, notify_user=False): if cls.has_account(user): - logger.debug("User %s has a XenForo account %s. Deleting." % (user, user.xenforo.username)) + logger.debug(f"User {user} has a XenForo account {user.xenforo.username}. Deleting.") if XenForoManager.disable_user(user.xenforo.username) == 200: user.xenforo.delete() if notify_user: diff --git a/allianceauth/services/modules/xenforo/tests.py b/allianceauth/services/modules/xenforo/tests.py index f0814359..5b68f46d 100644 --- a/allianceauth/services/modules/xenforo/tests.py +++ b/allianceauth/services/modules/xenforo/tests.py @@ -180,4 +180,4 @@ class XenforoManagerTestCase(TestCase): password = self.manager._XenForoManager__generate_password() self.assertEqual(len(password), 16) - self.assertIsInstance(password, type('')) + self.assertIsInstance(password, str) diff --git a/allianceauth/services/modules/xenforo/views.py b/allianceauth/services/modules/xenforo/views.py index 52e26c94..349b335c 100644 --- a/allianceauth/services/modules/xenforo/views.py +++ b/allianceauth/services/modules/xenforo/views.py @@ -21,7 +21,7 @@ ACCESS_PERM = 'xenforo.access_xenforo' def activate_xenforo_forum(request): logger.debug("activate_xenforo_forum called by user %s" % request.user) character = request.user.profile.main_character - logger.debug("Adding XenForo user for user %s with main character %s" % (request.user, character)) + logger.debug(f"Adding XenForo user for user {request.user} with main character {character}") result = XenForoManager.add_user(XenforoTasks.get_username(request.user), request.user.email) # Based on XenAPI's response codes if result['response']['status_code'] == 200: diff --git a/allianceauth/services/signals.py b/allianceauth/services/signals.py index 8f641c6d..34124a86 100644 --- a/allianceauth/services/signals.py +++ b/allianceauth/services/signals.py @@ -19,7 +19,7 @@ logger = logging.getLogger(__name__) @receiver(m2m_changed, sender=User.groups.through) def m2m_changed_user_groups(sender, instance, action, *args, **kwargs): - logger.debug("Received m2m_changed from %s groups with action %s" % (instance, action)) + logger.debug(f"Received m2m_changed from {instance} groups with action {action}") def trigger_service_group_update(): logger.debug("Triggering service group update for %s" % instance) @@ -29,7 +29,7 @@ def m2m_changed_user_groups(sender, instance, action, *args, **kwargs): svc.validate_user(instance) svc.update_groups(instance) except: - logger.exception('Exception running update_groups for services module %s on user %s' % (svc, instance)) + logger.exception(f'Exception running update_groups for services module {svc} on user {instance}') if instance.pk and (action == "post_add" or action == "post_remove" or action == "post_clear"): logger.debug("Waiting for commit to trigger service group update for %s" % instance) @@ -38,30 +38,30 @@ def m2m_changed_user_groups(sender, instance, action, *args, **kwargs): @receiver(m2m_changed, sender=User.user_permissions.through) def m2m_changed_user_permissions(sender, instance, action, *args, **kwargs): - logger.debug("Received m2m_changed from user %s permissions with action %s" % (instance, action)) + logger.debug(f"Received m2m_changed from user {instance} permissions with action {action}") logger.debug('sender: %s' % sender) if instance.pk and (action == "post_remove" or action == "post_clear"): - logger.debug("Permissions changed for user {}, re-validating services".format(instance)) + logger.debug(f"Permissions changed for user {instance}, re-validating services") # Checking permissions for a single user is quite fast, so we don't need to validate # That the permissions is a service permission, unlike groups. def validate_all_services(): - logger.debug("Validating all services for user {}".format(instance)) + logger.debug(f"Validating all services for user {instance}") for svc in ServicesHook.get_services(): try: svc.validate_user(instance) except: logger.exception( - 'Exception running validate_user for services module {} on user {}'.format(svc, instance)) + f'Exception running validate_user for services module {svc} on user {instance}') transaction.on_commit(lambda: validate_all_services()) @receiver(m2m_changed, sender=Group.permissions.through) def m2m_changed_group_permissions(sender, instance, action, pk_set, *args, **kwargs): - logger.debug("Received m2m_changed from group %s permissions with action %s" % (instance, action)) + logger.debug(f"Received m2m_changed from group {instance} permissions with action {action}") if instance.pk and (action == "post_remove" or action == "post_clear"): - logger.debug("Checking if service permission changed for group {}".format(instance)) + logger.debug(f"Checking if service permission changed for group {instance}") # As validating an entire groups service could lead to many thousands of permission checks # first we check that one of the permissions changed is, in fact, a service permission. perms = Permission.objects.filter(pk__in=pk_set) @@ -69,16 +69,16 @@ def m2m_changed_group_permissions(sender, instance, action, pk_set, *args, **kwa service_perms = [svc.access_perm for svc in ServicesHook.get_services()] for perm in perms: natural_key = perm.natural_key() - path_perm = "{}.{}".format(natural_key[1], natural_key[0]) + path_perm = f"{natural_key[1]}.{natural_key[0]}" if path_perm not in service_perms: # Not a service permission, keep searching continue for svc in ServicesHook.get_services(): if svc.access_perm == path_perm: - logger.debug("Permissions changed for group {} on service {}, re-validating services for groups users".format(instance, svc)) + logger.debug(f"Permissions changed for group {instance} on service {svc}, re-validating services for groups users") def validate_all_groups_users_for_service(): - logger.debug("Performing validation for service {}".format(svc)) + logger.debug(f"Performing validation for service {svc}") for user in instance.user_set.all(): svc.validate_user(user) @@ -86,14 +86,14 @@ def m2m_changed_group_permissions(sender, instance, action, pk_set, *args, **kwa got_change = True break # Found service, break out of services iteration and go back to permission iteration if not got_change: - logger.debug("Permission change for group {} was not service permission, ignoring".format(instance)) + logger.debug(f"Permission change for group {instance} was not service permission, ignoring") @receiver(m2m_changed, sender=State.permissions.through) def m2m_changed_state_permissions(sender, instance, action, pk_set, *args, **kwargs): - logger.debug("Received m2m_changed from state %s permissions with action %s" % (instance, action)) + logger.debug(f"Received m2m_changed from state {instance} permissions with action {action}") if instance.pk and (action == "post_remove" or action == "post_clear"): - logger.debug("Checking if service permission changed for state {}".format(instance)) + logger.debug(f"Checking if service permission changed for state {instance}") # As validating an entire groups service could lead to many thousands of permission checks # first we check that one of the permissions changed is, in fact, a service permission. perms = Permission.objects.filter(pk__in=pk_set) @@ -101,16 +101,16 @@ def m2m_changed_state_permissions(sender, instance, action, pk_set, *args, **kwa service_perms = [svc.access_perm for svc in ServicesHook.get_services()] for perm in perms: natural_key = perm.natural_key() - path_perm = "{}.{}".format(natural_key[1], natural_key[0]) + path_perm = f"{natural_key[1]}.{natural_key[0]}" if path_perm not in service_perms: # Not a service permission, keep searching continue for svc in ServicesHook.get_services(): if svc.access_perm == path_perm: - logger.debug("Permissions changed for state {} on service {}, re-validating services for state users".format(instance, svc)) + logger.debug(f"Permissions changed for state {instance} on service {svc}, re-validating services for state users") def validate_all_state_users_for_service(): - logger.debug("Performing validation for service {}".format(svc)) + logger.debug(f"Performing validation for service {svc}") for profile in instance.userprofile_set.all(): svc.validate_user(profile.user) @@ -118,12 +118,12 @@ def m2m_changed_state_permissions(sender, instance, action, pk_set, *args, **kwa got_change = True break # Found service, break out of services iteration and go back to permission iteration if not got_change: - logger.debug("Permission change for state {} was not service permission, ignoring".format(instance)) + logger.debug(f"Permission change for state {instance} was not service permission, ignoring") @receiver(state_changed) def check_service_accounts_state_changed(sender, user, state, **kwargs): - logger.debug("Received state_changed from %s to state %s" % (user, state)) + logger.debug(f"Received state_changed from {user} to state {state}") for svc in ServicesHook.get_services(): svc.validate_user(user) svc.update_groups(user) @@ -200,14 +200,14 @@ def process_main_character_update(sender, instance, *args, **kwargs): if not instance.character_name == old_instance.character_name or \ not instance.corporation_name == old_instance.corporation_name or \ not instance.alliance_name == old_instance.alliance_name: - logger.info("syncing service nickname for user {0}".format(instance.userprofile.user)) + logger.info(f"syncing service nickname for user {instance.userprofile.user}") for svc in ServicesHook.get_services(): try: svc.validate_user(instance.userprofile.user) svc.sync_nickname(instance.userprofile.user) except: - logger.exception('Exception running sync_nickname for services module %s on user %s' % (svc, instance)) + logger.exception(f'Exception running sync_nickname for services module {svc} on user {instance}') except ObjectDoesNotExist: # not a main char ignore pass diff --git a/allianceauth/services/tasks.py b/allianceauth/services/tasks.py index 519ec086..cac663c6 100644 --- a/allianceauth/services/tasks.py +++ b/allianceauth/services/tasks.py @@ -33,13 +33,13 @@ class DjangoBackend: @shared_task(bind=True) def validate_services(self, pk): user = User.objects.get(pk=pk) - logger.debug('Ensuring user {} has permissions for active services'.format(user)) + logger.debug(f'Ensuring user {user} has permissions for active services') # Iterate through services hooks and have them check the validity of the user for svc in ServicesHook.get_services(): try: svc.validate_user(user) except: - logger.exception('Exception running validate_user for services module %s on user %s' % (svc, user)) + logger.exception(f'Exception running validate_user for services module {svc} on user {user}') def disable_user(user): diff --git a/allianceauth/srp/managers.py b/allianceauth/srp/managers.py index 2e265ba9..bc01bd22 100644 --- a/allianceauth/srp/managers.py +++ b/allianceauth/srp/managers.py @@ -42,11 +42,11 @@ class SRPManager: if km: ship_type = km['victim']['ship_type_id'] logger.debug( - "Ship type for kill ID %s is %s" % (kill_id, ship_type) + f"Ship type for kill ID {kill_id} is {ship_type}" ) ship_value = result['zkb']['totalValue'] logger.debug( - "Total loss value for kill id %s is %s" % (kill_id, ship_value) + f"Total loss value for kill id {kill_id} is {ship_value}" ) victim_id = km['victim']['character_id'] return ship_type, ship_value, victim_id diff --git a/allianceauth/srp/migrations/0001_initial.py b/allianceauth/srp/migrations/0001_initial.py index b6344eb4..db51307b 100644 --- a/allianceauth/srp/migrations/0001_initial.py +++ b/allianceauth/srp/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:40 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/srp/migrations/0002_srpuserrequest_srp_status_choices.py b/allianceauth/srp/migrations/0002_srpuserrequest_srp_status_choices.py index 24700804..f81a44d8 100644 --- a/allianceauth/srp/migrations/0002_srpuserrequest_srp_status_choices.py +++ b/allianceauth/srp/migrations/0002_srpuserrequest_srp_status_choices.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-01-18 20:21 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/srp/migrations/0003_make_strings_more_stringy.py b/allianceauth/srp/migrations/0003_make_strings_more_stringy.py index 24b40a01..18a88547 100644 --- a/allianceauth/srp/migrations/0003_make_strings_more_stringy.py +++ b/allianceauth/srp/migrations/0003_make_strings_more_stringy.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:35 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/srp/migrations/0004_on_delete.py b/allianceauth/srp/migrations/0004_on_delete.py index d42e390d..3dbd2083 100644 --- a/allianceauth/srp/migrations/0004_on_delete.py +++ b/allianceauth/srp/migrations/0004_on_delete.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/allianceauth/srp/models.py b/allianceauth/srp/models.py index b3ebc7d9..bb4f8280 100755 --- a/allianceauth/srp/models.py +++ b/allianceauth/srp/models.py @@ -18,7 +18,7 @@ class SrpFleetMain(models.Model): @property def total_cost(self): - return sum([int(r.srp_total_amount) for r in self.srpuserrequest_set.all()]) + return sum(int(r.srp_total_amount) for r in self.srpuserrequest_set.all()) @property def pending_requests(self): diff --git a/allianceauth/srp/tests/test_managers.py b/allianceauth/srp/tests/test_managers.py index 3f416c14..91fe4968 100755 --- a/allianceauth/srp/tests/test_managers.py +++ b/allianceauth/srp/tests/test_managers.py @@ -22,7 +22,7 @@ currentdir = os.path.dirname(os.path.abspath(inspect.getfile( def load_data(filename): """loads given JSON file from `testdata` sub folder and returns content""" with open( - currentdir + '/testdata/%s.json' % filename, 'r', encoding='utf-8' + currentdir + '/testdata/%s.json' % filename, encoding='utf-8' ) as f: data = json.load(f) diff --git a/allianceauth/srp/views.py b/allianceauth/srp/views.py index 404904ec..e905d893 100755 --- a/allianceauth/srp/views.py +++ b/allianceauth/srp/views.py @@ -47,7 +47,7 @@ def srp_management(request, all=False): @login_required @permission_required('srp.access_srp') def srp_fleet_view(request, fleet_id): - logger.debug("srp_fleet_view called by user %s for fleet id %s" % (request.user, fleet_id)) + logger.debug(f"srp_fleet_view called by user {request.user} for fleet id {fleet_id}") try: fleet_main = SrpFleetMain.objects.get(id=fleet_id) except SrpFleetMain.DoesNotExist: @@ -81,7 +81,7 @@ def srp_fleet_add_view(request): completed = True completed_srp_code = srp_fleet_main.fleet_srp_code - logger.info("Created SRP Fleet %s by user %s" % (srp_fleet_main.fleet_name, request.user)) + logger.info(f"Created SRP Fleet {srp_fleet_main.fleet_name} by user {request.user}") messages.success(request, _('Created SRP fleet %(fleetname)s.') % {"fleetname": srp_fleet_main.fleet_name}) else: @@ -96,10 +96,10 @@ def srp_fleet_add_view(request): @login_required @permission_required('auth.srp_management') def srp_fleet_remove(request, fleet_id): - logger.debug("srp_fleet_remove called by user %s for fleet id %s" % (request.user, fleet_id)) + logger.debug(f"srp_fleet_remove called by user {request.user} for fleet id {fleet_id}") srpfleetmain = get_object_or_404(SrpFleetMain, id=fleet_id) srpfleetmain.delete() - logger.info("SRP Fleet %s deleted by user %s" % (srpfleetmain.fleet_name, request.user)) + logger.info(f"SRP Fleet {srpfleetmain.fleet_name} deleted by user {request.user}") messages.success(request, _('Removed SRP fleet %(fleetname)s.') % {"fleetname": srpfleetmain.fleet_name}) return redirect("srp:management") @@ -107,11 +107,11 @@ def srp_fleet_remove(request, fleet_id): @login_required @permission_required('auth.srp_management') def srp_fleet_disable(request, fleet_id): - logger.debug("srp_fleet_disable called by user %s for fleet id %s" % (request.user, fleet_id)) + logger.debug(f"srp_fleet_disable called by user {request.user} for fleet id {fleet_id}") srpfleetmain = get_object_or_404(SrpFleetMain, id=fleet_id) srpfleetmain.fleet_srp_code = "" srpfleetmain.save() - logger.info("SRP Fleet %s disabled by user %s" % (srpfleetmain.fleet_name, request.user)) + logger.info(f"SRP Fleet {srpfleetmain.fleet_name} disabled by user {request.user}") messages.success(request, _('Disabled SRP fleet %(fleetname)s.') % {"fleetname": srpfleetmain.fleet_name}) return redirect("srp:management") @@ -119,11 +119,11 @@ def srp_fleet_disable(request, fleet_id): @login_required @permission_required('auth.srp_management') def srp_fleet_enable(request, fleet_id): - logger.debug("srp_fleet_enable called by user %s for fleet id %s" % (request.user, fleet_id)) + logger.debug(f"srp_fleet_enable called by user {request.user} for fleet id {fleet_id}") srpfleetmain = get_object_or_404(SrpFleetMain, id=fleet_id) srpfleetmain.fleet_srp_code = random_string(8) srpfleetmain.save() - logger.info("SRP Fleet %s enable by user %s" % (srpfleetmain.fleet_name, request.user)) + logger.info(f"SRP Fleet {srpfleetmain.fleet_name} enable by user {request.user}") messages.success(request, _('Enabled SRP fleet %(fleetname)s.') % {"fleetname": srpfleetmain.fleet_name}) return redirect("srp:management") @@ -131,11 +131,11 @@ def srp_fleet_enable(request, fleet_id): @login_required @permission_required('auth.srp_management') def srp_fleet_mark_completed(request, fleet_id): - logger.debug("srp_fleet_mark_completed called by user %s for fleet id %s" % (request.user, fleet_id)) + logger.debug(f"srp_fleet_mark_completed called by user {request.user} for fleet id {fleet_id}") srpfleetmain = get_object_or_404(SrpFleetMain, id=fleet_id) srpfleetmain.fleet_srp_status = "Completed" srpfleetmain.save() - logger.info("Marked SRP Fleet %s as completed by user %s" % (srpfleetmain.fleet_name, request.user)) + logger.info(f"Marked SRP Fleet {srpfleetmain.fleet_name} as completed by user {request.user}") messages.success(request, _('Marked SRP fleet %(fleetname)s as completed.') % {"fleetname": srpfleetmain.fleet_name}) return redirect("srp:fleet", fleet_id) @@ -144,11 +144,11 @@ def srp_fleet_mark_completed(request, fleet_id): @login_required @permission_required('auth.srp_management') def srp_fleet_mark_uncompleted(request, fleet_id): - logger.debug("srp_fleet_mark_uncompleted called by user %s for fleet id %s" % (request.user, fleet_id)) + logger.debug(f"srp_fleet_mark_uncompleted called by user {request.user} for fleet id {fleet_id}") srpfleetmain = get_object_or_404(SrpFleetMain, id=fleet_id) srpfleetmain.fleet_srp_status = "" srpfleetmain.save() - logger.info("Marked SRP Fleet %s as incomplete for user %s" % (fleet_id, request.user)) + logger.info(f"Marked SRP Fleet {fleet_id} as incomplete for user {request.user}") messages.success(request, _('Marked SRP fleet %(fleetname)s as incomplete.') % {"fleetname": srpfleetmain.fleet_name}) return redirect("srp:fleet", fleet_id) @@ -157,10 +157,10 @@ def srp_fleet_mark_uncompleted(request, fleet_id): @login_required @permission_required('srp.access_srp') def srp_request_view(request, fleet_srp): - logger.debug("srp_request_view called by user %s for fleet srp code %s" % (request.user, fleet_srp)) + logger.debug(f"srp_request_view called by user {request.user} for fleet srp code {fleet_srp}") if SrpFleetMain.objects.filter(fleet_srp_code=fleet_srp).exists() is False: - logger.error("Unable to locate SRP Fleet using code %s for user %s" % (fleet_srp, request.user)) + logger.error(f"Unable to locate SRP Fleet using code {fleet_srp} for user {request.user}") messages.error(request, _('Unable to locate SRP code with ID %(srpfleetid)s') % {"srpfleetid": fleet_srp}) return redirect("srp:management") @@ -193,7 +193,7 @@ def srp_request_view(request, fleet_srp): srp_kill_link = SRPManager.get_kill_id(srp_request.killboard_link) (ship_type_id, ship_value, victim_id) = SRPManager.get_kill_data(srp_kill_link) except ValueError: - logger.debug("User %s Submitted Invalid Killmail Link %s or server could not be reached" % ( + logger.debug("User {} Submitted Invalid Killmail Link {} or server could not be reached".format( request.user, srp_request.killboard_link)) # THIS SHOULD BE IN FORM VALIDATION messages.error(request, @@ -205,7 +205,7 @@ def srp_request_view(request, fleet_srp): srp_request.kb_total_loss = ship_value srp_request.post_time = post_time srp_request.save() - logger.info("Created SRP Request on behalf of user %s for fleet name %s" % ( + logger.info("Created SRP Request on behalf of user {} for fleet name {}".format( request.user, srp_fleet_main.fleet_name)) messages.success(request, _('Submitted SRP request for your %(ship)s.') % {"ship": srp_request.srp_ship_name}) @@ -228,7 +228,7 @@ def srp_request_view(request, fleet_srp): @permission_required('auth.srp_management') def srp_request_remove(request): numrequests = len(request.POST) - 1 - logger.debug("srp_request_remove called by user %s for %s srp request id's" % (request.user, numrequests)) + logger.debug(f"srp_request_remove called by user {request.user} for {numrequests} srp request id's") stored_fleet_view = None for srp_request_id in request.POST: if numrequests == 0: @@ -240,7 +240,7 @@ def srp_request_remove(request): srpuserrequest = SrpUserRequest.objects.get(id=srp_request_id) stored_fleet_view = srpuserrequest.srp_fleet_main.id srpuserrequest.delete() - logger.info("Deleted SRP request id %s for user %s" % (srp_request_id, request.user)) + logger.info(f"Deleted SRP request id {srp_request_id} for user {request.user}") if stored_fleet_view is None: logger.error("Unable to delete srp requests for user %s - request matching id not found." % (request.user)) messages.error(request, _('Unable to locate selected SRP request.')) @@ -254,7 +254,7 @@ def srp_request_remove(request): @permission_required('auth.srp_management') def srp_request_approve(request): numrequests = len(request.POST) - 1 - logger.debug("srp_request_approve called by user %s for %s srp request id's" % (request.user, numrequests)) + logger.debug(f"srp_request_approve called by user {request.user} for {numrequests} srp request id's") stored_fleet_view = None for srp_request_id in request.POST: if numrequests == 0: @@ -269,13 +269,13 @@ def srp_request_approve(request): if srpuserrequest.srp_total_amount == 0: srpuserrequest.srp_total_amount = srpuserrequest.kb_total_loss srpuserrequest.save() - logger.info("Approved SRP request id %s for character %s by user %s" % ( + logger.info("Approved SRP request id {} for character {} by user {}".format( srp_request_id, srpuserrequest.character, request.user)) notify( srpuserrequest.character.character_ownership.user, 'SRP Request Approved', level='success', - message='Your SRP request for a %s lost during %s has been approved for %s ISK.' % ( + message='Your SRP request for a {} lost during {} has been approved for {} ISK.'.format( srpuserrequest.srp_ship_name, srpuserrequest.srp_fleet_main.fleet_name, intcomma(srpuserrequest.srp_total_amount)) ) @@ -292,7 +292,7 @@ def srp_request_approve(request): @permission_required('auth.srp_management') def srp_request_reject(request): numrequests = len(request.POST) - 1 - logger.debug("srp_request_reject called by user %s for %s srp request id's" % (request.user, numrequests)) + logger.debug(f"srp_request_reject called by user {request.user} for {numrequests} srp request id's") stored_fleet_view = None for srp_request_id in request.POST: if numrequests == 0: @@ -305,13 +305,13 @@ def srp_request_reject(request): stored_fleet_view = srpuserrequest.srp_fleet_main.id srpuserrequest.srp_status = "Rejected" srpuserrequest.save() - logger.info("SRP request id %s for character %s rejected by %s" % ( + logger.info("SRP request id {} for character {} rejected by {}".format( srp_request_id, srpuserrequest.character, request.user)) notify( srpuserrequest.character.character_ownership.user, 'SRP Request Rejected', level='danger', - message='Your SRP request for a %s lost during %s has been rejected.' % ( + message='Your SRP request for a {} lost during {} has been rejected.'.format( srpuserrequest.srp_ship_name, srpuserrequest.srp_fleet_main.fleet_name) ) if stored_fleet_view is None: @@ -326,11 +326,11 @@ def srp_request_reject(request): @login_required @permission_required('auth.srp_management') def srp_request_update_amount(request, fleet_srp_request_id): - logger.debug("srp_request_update_amount called by user %s for fleet srp request id %s" % ( + logger.debug("srp_request_update_amount called by user {} for fleet srp request id {}".format( request.user, fleet_srp_request_id)) if SrpUserRequest.objects.filter(id=fleet_srp_request_id).exists() is False: - logger.error("Unable to locate SRP request id %s for user %s" % (fleet_srp_request_id, request.user)) + logger.error(f"Unable to locate SRP request id {fleet_srp_request_id} for user {request.user}") messages.error(request, _('Unable to locate SRP request with ID %(requestid)s') % {"requestid": fleet_srp_request_id}) return redirect("srp:management") @@ -338,7 +338,7 @@ def srp_request_update_amount(request, fleet_srp_request_id): srp_request = SrpUserRequest.objects.get(id=fleet_srp_request_id) srp_request.srp_total_amount = request.POST['value'] srp_request.save() - logger.info("Updated srp request id %s total to %s by user %s" % ( + logger.info("Updated srp request id {} total to {} by user {}".format( fleet_srp_request_id, request.POST['value'], request.user)) return JsonResponse({"success": True, "pk": fleet_srp_request_id, "newValue": request.POST['value']}) @@ -346,7 +346,7 @@ def srp_request_update_amount(request, fleet_srp_request_id): @login_required @permission_required('auth.srp_management') def srp_fleet_edit_view(request, fleet_id): - logger.debug("srp_fleet_edit_view called by user %s for fleet id %s" % (request.user, fleet_id)) + logger.debug(f"srp_fleet_edit_view called by user {request.user} for fleet id {fleet_id}") srpfleetmain = get_object_or_404(SrpFleetMain, id=fleet_id) if request.method == 'POST': form = SrpFleetMainUpdateForm(request.POST) @@ -354,7 +354,7 @@ def srp_fleet_edit_view(request, fleet_id): if form.is_valid(): srpfleetmain.fleet_srp_aar_link = form.cleaned_data['fleet_aar_link'] srpfleetmain.save() - logger.info("User %s edited SRP Fleet %s" % (request.user, srpfleetmain.fleet_name)) + logger.info(f"User {request.user} edited SRP Fleet {srpfleetmain.fleet_name}") messages.success(request, _('Saved changes to SRP fleet %(fleetname)s') % {"fleetname": srpfleetmain.fleet_name}) return redirect("srp:management") diff --git a/allianceauth/templatetags/admin_status.py b/allianceauth/templatetags/admin_status.py index 94c6be63..9b652286 100644 --- a/allianceauth/templatetags/admin_status.py +++ b/allianceauth/templatetags/admin_status.py @@ -158,13 +158,13 @@ def _latests_versions(tags: list) -> tuple: versions.append(version) latest_version = latest_patch_version = max(versions) - latest_major_version = min([ + latest_major_version = min( v for v in versions if v.major == latest_version.major - ]) - latest_minor_version = min([ + ) + latest_minor_version = min( v for v in versions if v.major == latest_version.major and v.minor == latest_version.minor - ]) + ) latest_beta_version = max(betas) return ( latest_major_version, diff --git a/allianceauth/thirdparty/navhelper/templatetags/navactive.py b/allianceauth/thirdparty/navhelper/templatetags/navactive.py index 89abed90..4bd91698 100644 --- a/allianceauth/thirdparty/navhelper/templatetags/navactive.py +++ b/allianceauth/thirdparty/navhelper/templatetags/navactive.py @@ -51,13 +51,13 @@ def navactive(request, urls): if resolved.url_name: resolved_urls.add(resolved.url_name) if resolved.namespaces: - resolved_urls = resolved_urls.union(["{}:{}".format(namespace, resolved.url_name) for namespace in resolved.namespaces]) - resolved_urls = resolved_urls.union(["{}:".format(namespace) for namespace in resolved.namespaces]) + resolved_urls = resolved_urls.union([f"{namespace}:{resolved.url_name}" for namespace in resolved.namespaces]) + resolved_urls = resolved_urls.union([f"{namespace}:" for namespace in resolved.namespaces]) if getattr(resolved, 'app_name', None): - resolved_urls = resolved_urls.union(["{}:{}".format(resolved.app_name, resolved.url_name), "{}:".format(resolved.app_name)]) + resolved_urls = resolved_urls.union([f"{resolved.app_name}:{resolved.url_name}", f"{resolved.app_name}:"]) if getattr(resolved, 'app_names', []): - resolved_urls = resolved_urls.union(["{}:{}".format(app_name, resolved.url_name) for app_name in resolved.app_names]) - resolved_urls = resolved_urls.union(["{}:".format(app_name) for app_name in resolved.app_names]) + resolved_urls = resolved_urls.union([f"{app_name}:{resolved.url_name}" for app_name in resolved.app_names]) + resolved_urls = resolved_urls.union([f"{app_name}:" for app_name in resolved.app_names]) if url_list and resolved_urls and bool(resolved_urls & url_list): return getattr(settings, "NAVHELPER_ACTIVE_CLASS", "active") return getattr(settings, "NAVHELPER_NOT_ACTIVE_CLASS", "") diff --git a/allianceauth/timerboard/form.py b/allianceauth/timerboard/form.py index abaa50b8..d8dc9e71 100755 --- a/allianceauth/timerboard/form.py +++ b/allianceauth/timerboard/form.py @@ -30,7 +30,7 @@ class TimerForm(forms.ModelForm): if 'minutes_left' not in initial: initial.update({'minutes_left': td.seconds // 60 % 60}) kwargs.update({'initial': initial}) - super(TimerForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) structure_choices = [('POCO', 'POCO'), ('I-HUB', 'I-HUB'), @@ -69,7 +69,7 @@ class TimerForm(forms.ModelForm): corp_timer = forms.BooleanField(label=_("Corp-Restricted"), required=False) def save(self, commit=True): - timer = super(TimerForm, self).save(commit=False) + timer = super().save(commit=False) # Get character character = self.user.profile.main_character @@ -82,7 +82,7 @@ class TimerForm(forms.ModelForm): current_time = timezone.now() eve_time = current_time + future_time logger.debug( - "Determined timer eve time is %s - current time %s, adding %s" % (eve_time, current_time, future_time)) + f"Determined timer eve time is {eve_time} - current time {current_time}, adding {future_time}") timer.eve_time = eve_time timer.eve_character = character diff --git a/allianceauth/timerboard/migrations/0001_initial.py b/allianceauth/timerboard/migrations/0001_initial.py index a7095e89..6f8d5e1c 100644 --- a/allianceauth/timerboard/migrations/0001_initial.py +++ b/allianceauth/timerboard/migrations/0001_initial.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.1 on 2016-09-05 21:40 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/timerboard/migrations/0002_make_strings_more_stringy.py b/allianceauth/timerboard/migrations/0002_make_strings_more_stringy.py index 6a222cb5..79749282 100644 --- a/allianceauth/timerboard/migrations/0002_make_strings_more_stringy.py +++ b/allianceauth/timerboard/migrations/0002_make_strings_more_stringy.py @@ -1,5 +1,4 @@ # Generated by Django 1.10.5 on 2017-03-22 23:35 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/allianceauth/timerboard/migrations/0003_on_delete.py b/allianceauth/timerboard/migrations/0003_on_delete.py index 0fa56146..1a3013b0 100644 --- a/allianceauth/timerboard/migrations/0003_on_delete.py +++ b/allianceauth/timerboard/migrations/0003_on_delete.py @@ -1,5 +1,4 @@ # Generated by Django 1.11.5 on 2017-09-28 02:16 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/allianceauth/timerboard/views.py b/allianceauth/timerboard/views.py index 3f22596b..ebc4715b 100755 --- a/allianceauth/timerboard/views.py +++ b/allianceauth/timerboard/views.py @@ -26,7 +26,7 @@ class TimerView(BaseTimerView): permission_required = 'auth.timer_view' def get(self, request): - logger.debug("timer_view called by user {}".format(request.user)) + logger.debug(f"timer_view called by user {request.user}") char = request.user.profile.main_character if char: corp = char.corporation @@ -59,7 +59,7 @@ class AddUpdateMixin: """ Inject the request user into the kwargs passed to the form """ - kwargs = super(AddUpdateMixin, self).get_form_kwargs() + kwargs = super().get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs @@ -68,9 +68,9 @@ class AddTimerView(TimerManagementView, AddUpdateMixin, CreateView): template_name_suffix = '_create_form' def form_valid(self, form): - result = super(AddTimerView, self).form_valid(form) + result = super().form_valid(form) timer = self.object - logger.info("Created new timer in {} at {} by user {}".format(timer.system, timer.eve_time, self.request.user)) + logger.info(f"Created new timer in {timer.system} at {timer.eve_time} by user {self.request.user}") messages.success(self.request, _('Added new timer in %(system)s at %(time)s.') % {"system": timer.system, "time": timer.eve_time}) return result @@ -80,7 +80,7 @@ class EditTimerView(TimerManagementView, AddUpdateMixin, UpdateView): def form_valid(self, form): messages.success(self.request, _('Saved changes to the timer.')) - return super(EditTimerView, self).form_valid(form) + return super().form_valid(form) class RemoveTimerView(TimerManagementView, DeleteView): diff --git a/docs/conf.py b/docs/conf.py index 6fdd1a7d..682a0653 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -58,16 +58,16 @@ source_suffix = ['.md', '.rst'] master_doc = 'index' # General information about the project. -project = u'Alliance Auth' -copyright = u'2018-2020, Alliance Auth' -author = u'R4stl1n' +project = 'Alliance Auth' +copyright = '2018-2020, Alliance Auth' +author = 'R4stl1n' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = u'2.0' +version = '2.0' # The full version, including alpha/beta/rc tags. # release = u'1.14.0' @@ -142,7 +142,7 @@ latex_elements = { # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - (master_doc, 'AllianceAuth.tex', u'Alliance Auth Documentation', u'R4stl1n', 'manual'), + (master_doc, 'AllianceAuth.tex', 'Alliance Auth Documentation', 'R4stl1n', 'manual'), ] @@ -151,7 +151,7 @@ latex_documents = [ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - (master_doc, 'allianceauth', u'Alliance Auth Documentation', + (master_doc, 'allianceauth', 'Alliance Auth Documentation', [author], 1) ] @@ -165,7 +165,7 @@ add_module_names = False # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - (master_doc, 'AllianceAuth', u'Alliance Auth Documentation', + (master_doc, 'AllianceAuth', 'Alliance Auth Documentation', author, 'AllianceAuth', 'An auth system for EVE Online to help in-game organizations manage online service access.', 'Miscellaneous'), ]