Skip to content

ruff pyupgrade #942

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion askbot/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
:synopsis: connector to standard Django admin interface

Expand Down
13 changes: 6 additions & 7 deletions askbot/bin/generate_modules.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Miville
# Copyright (C) 2008 Société des arts technologiques (SAT)
# http://www.sat.qc.ca
Expand Down Expand Up @@ -39,7 +38,7 @@

def create_file_name(base, opts):
"""Create file name from base name, path and suffix"""
return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix))
return os.path.join(opts.destdir, f"{base}.{opts.suffix}")


def write_automodule_directive(module):
Expand All @@ -61,13 +60,13 @@ def write_heading(module, kind='Module'):

def write_sub(module, kind='Module'):
"""Create the module subtitle"""
sub = title_line('The :mod:`%s` %s' % (module, kind), '-')
sub = title_line(f'The :mod:`{module}` {kind}', '-')
return sub


def title_line(title, char):
""" Underline the title with the character pass, with the right length."""
return ':mod:`%s`\n%s\n\n' % (title, len(title) * char)
return f':mod:`{title}`\n{len(title) * char}\n\n'


def create_module_content(module):
Expand Down Expand Up @@ -108,7 +107,7 @@ def create_package_content(package, py_files, sub_packages):
# __init__.py of the current module
continue
py_file = os.path.splitext(py_file)[0]
text += '* :ref:`%s.%s`\n' % (package, py_file)
text += f'* :ref:`{package}.{py_file}`\n'
text += '\n'

# create links to sub-packages
Expand All @@ -119,7 +118,7 @@ def create_package_content(package, py_files, sub_packages):
text += '\n'
for sub in sub_packages:
# TODO - add description here
text += '* :ref:`%s.%s`\n' % (package, sub)
text += f'* :ref:`{package}.{sub}`\n'
return text
# build toctree for the package page
# text += '.. toctree::\n\n'
Expand Down Expand Up @@ -149,7 +148,7 @@ def check_for_code(module):
"""
Check if there's at least one class or one function in the module.
"""
fd = open(module, 'r')
fd = open(module)
for line in fd:
if line.startswith('def ') or line.startswith('class '):
fd.close()
Expand Down
6 changes: 3 additions & 3 deletions askbot/conf/settings_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def assert_setting_info_correct(info):
assert isinstance(info[2], bool)


class ConfigSettings(object):
class ConfigSettings:
"""A very simple Singleton wrapper for settings
a limitation is that all settings names using this class
must be distinct, even though they might belong
Expand Down Expand Up @@ -139,7 +139,7 @@ def get_setting_url(self, data):
'livesettings_group',
setting_name, # TODO: better use description
kwargs={'group': group_name},
anchor='id_%s__%s__%s' % (group_name, setting_name, get_language())
anchor=f'id_{group_name}__{setting_name}__{get_language()}'
)
if len(data) == 4:
return force_str(format_lazy('{} ({})',link, data[3]))
Expand Down Expand Up @@ -227,7 +227,7 @@ def prime_cache(cls, cache_key, **kwargs):
else:
setting_value = cls.__instance[key]
if setting_value.localized:
db_key = '{}_{}'.format(key, format_setting_name(get_language()))
db_key = f'{key}_{format_setting_name(get_language())}'
else:
db_key = key

Expand Down
3 changes: 1 addition & 2 deletions askbot/const/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# encoding:utf-8
"""
All constants could be used in other modules
For reasons that models, views can't have unicode
Expand Down Expand Up @@ -179,7 +178,7 @@
TAG_CHARS = r'\wp{M}+.#-'
TAG_FIRST_CHARS = r'[\wp{M}]'
TAG_FORBIDDEN_FIRST_CHARS = r'#'
TAG_REGEX_BARE = r'%s[%s]+' % (TAG_FIRST_CHARS, TAG_CHARS)
TAG_REGEX_BARE = rf'{TAG_FIRST_CHARS}[{TAG_CHARS}]+'
TAG_REGEX = r'^%s$' % TAG_REGEX_BARE

TAG_STRIP_CHARS = ', '
Expand Down
2 changes: 1 addition & 1 deletion askbot/deployment/deployers/file_deployer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def get_template_parameters(self): # pylint: disable=no-self-use

def get_template(self):
"""Returns string representation of the template"""
return open(get_askbot_module_path(self.template_path), 'r').read()
return open(get_askbot_module_path(self.template_path)).read()

def deploy_file(self, contents):
"""Writes contents into the target file"""
Expand Down
2 changes: 1 addition & 1 deletion askbot/deployment/deployers/settings_py_admins_snippet.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ def render(self):
"""--admin-settings override the default"""
if self.params['admin_settings']:
return self.params['admin_settings']
return super(SettingsPyAdminsSnippet, self).render()
return super().render()
2 changes: 1 addition & 1 deletion askbot/deployment/deployers/settings_py_caching_snippet.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ class SettingsPyCachingSnippet(FileDeployer): # pylint: disable=missing-class-do
def render(self):
if self.params['caching_settings']:
return self.params['caching_settings']
return super(SettingsPyCachingSnippet, self).render()
return super().render()
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ def render(self):
`database_settings` parameter"""
if self.params['database_settings']:
return self.params['database_settings']
return super(SettingsPyDatabasesSnippet, self).render()
return super().render()
2 changes: 1 addition & 1 deletion askbot/deployment/deployers/settings_py_email_snippet.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,4 @@ def render(self):
parameter"""
if self.params['email_settings']:
return self.params['email_settings']
return super(SettingsPyEmailSnippet, self).render()
return super().render()
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ def render(self):
the override with the `language_settings` parameter"""
if self.params['language_settings']:
return self.params['language_settings']
return super(SettingsPyLanguagesSnippet, self).render()
return super().render()
2 changes: 1 addition & 1 deletion askbot/deployment/deployers/settings_py_logging_snippet.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ def render(self):
allows override with the --logging-settings parameter"""
if self.params['logging_settings']:
return self.params['logging_settings']
return super(SettingsPyLoggingSnippet, self).render()
return super().render()
2 changes: 1 addition & 1 deletion askbot/deployment/path_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def dir_has_django_project(directory):
if file_name.endswith(os.path.sep + 'manage.py'):
#a hack allowing to install into the project directory
continue
with open(file_name, 'r') as py_file:
with open(file_name) as py_file:
for line in py_file:
if IMPORT_RE1.match(line) or IMPORT_RE2.match(line):
return True
Expand Down
2 changes: 1 addition & 1 deletion askbot/deployment/validators/proj_dir_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class ProjDirValidator(DirValidator):
"""Implements the .clean method for the proj_name parameter"""

def __init__(self, console, parser, root_dir):
super(ProjDirValidator, self).__init__(console, parser)
super().__init__(console, parser)
self.user_prompt = f'Enter {const.PROJ_NAME_HELP}.'
self.option_name = 'proj_name'
self.root_dir = root_dir
Expand Down
2 changes: 1 addition & 1 deletion askbot/deployment/validators/root_dir_validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class RootDirValidator(DirValidator):
by providing the .clean method"""

def __init__(self, console, parser):
super(RootDirValidator, self).__init__(console, parser)
super().__init__(console, parser)
self.user_prompt = f'Enter {const.ROOT_DIR_HELP}.'
self.option_name = 'root_dir'
self.default = './' + const.DEFAULT_PROJECT_NAME
Expand Down
1 change: 0 additions & 1 deletion askbot/deps/django_authopenid/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2007, 2008, Benoît Chesneau
#
# All rights reserved.
Expand Down
1 change: 0 additions & 1 deletion askbot/deps/django_authopenid/admin.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

from django.contrib import admin
from askbot.deps.django_authopenid.models import UserAssociation
Expand Down
6 changes: 3 additions & 3 deletions askbot/deps/django_authopenid/backends.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

LOG = logging.getLogger(__name__)

class AuthBackend(object):
class AuthBackend:
"""Authenticator's authentication backend class
for more info, see django doc page:
http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend
Expand All @@ -31,7 +31,7 @@ class AuthBackend(object):
"""
def __init__(self, *args, **kwargs):
self.login_providers = util.get_enabled_login_providers()
super(AuthBackend, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def authenticate(self, request, method=None, provider_name=None, **kwargs):
"""this authentication function supports many login methods"""
Expand Down Expand Up @@ -143,7 +143,7 @@ def auth_by_external_password(self, provider_name, username, password, request):
else:
#have username collision - so make up a more unique user name
#bug: - if user already exists with the new username - we are in trouble
new_username = '%s@%s' % (username, provider_name)
new_username = f'{username}@{provider_name}'
user = User.objects.create_user(new_username, '', password)
user_registered.send(None, user=user, request=request)
message = _(
Expand Down
17 changes: 8 additions & 9 deletions askbot/deps/django_authopenid/forms.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2007, 2008, Benoît Chesneau
#
# All rights reserved.
Expand Down Expand Up @@ -53,7 +52,7 @@

class ConsentField(forms.BooleanField):
def __init__(self, *args, **kwargs):
super(ConsentField, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.label = _('I have read and agree with the terms of service')
self.required = True
self.error_messages['required'] = _(
Expand All @@ -68,7 +67,7 @@ class LoginProviderField(forms.CharField):

def __init__(self, *args, **kwargs):
kwargs['max_length'] = 64
super(LoginProviderField, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def clean(self, value):
"""makes sure that login provider name
Expand Down Expand Up @@ -301,7 +300,7 @@ class RegistrationForm(forms.Form):

def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super(RegistrationForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
email_required = not askbot_settings.BLANK_EMAIL_ALLOWED
self.fields['email'] = UserEmailField(required=email_required)
if askbot_settings.TERMS_CONSENT_REQUIRED:
Expand All @@ -313,7 +312,7 @@ def __init__(self, *args, **kwargs):
def clean(self):
if askbot_settings.NEW_REGISTRATIONS_DISABLED:
raise forms.ValidationError(askbot_settings.NEW_REGISTRATIONS_DISABLED_MESSAGE)
return super(RegistrationForm, self).clean()
return super().clean()


class PasswordRegistrationForm(RegistrationForm, SetPasswordForm):
Expand Down Expand Up @@ -361,7 +360,7 @@ class ChangeEmailForm(forms.Form):
""" change email form """
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None, \
initial=None, user=None):
super(ChangeEmailForm, self).__init__(data, files, auto_id,
super().__init__(data, files, auto_id,
prefix, initial)
email_required = not askbot_settings.BLANK_EMAIL_ALLOWED
self.fields['email'] = UserEmailField(skip_clean=True, required=email_required)
Expand Down Expand Up @@ -416,7 +415,7 @@ class ChangeopenidForm(forms.Form):
def __init__(self, data=None, user=None, *args, **kwargs):
if user is None:
raise TypeError("Keyword argument 'user' must be supplied")
super(ChangeopenidForm, self).__init__(data, *args, **kwargs)
super().__init__(data, *args, **kwargs)
self.user = user


Expand All @@ -428,7 +427,7 @@ class DeleteForm(forms.Form):

def __init__(self, data=None, files=None, auto_id='id_%s',
prefix=None, initial=None, user=None):
super(DeleteForm, self).__init__(data, files, auto_id, prefix, initial)
super().__init__(data, files, auto_id, prefix, initial)
self.test_openid = False
self.user = user

Expand All @@ -449,7 +448,7 @@ class EmailPasswordForm(forms.Form):

def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None):
super(EmailPasswordForm, self).__init__(data, files, auto_id,
super().__init__(data, files, auto_id,
prefix, initial)
self.user_cache = None

Expand Down
2 changes: 1 addition & 1 deletion askbot/deps/django_authopenid/ldap_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def ldap_create_user_default(user_info, request):
user.is_active = True
user.save()
user_registered.send(None, user=user, request=request)
LOG.info('Created New User : [{0}]'.format(user_info['ldap_username']))
LOG.info('Created New User : [{}]'.format(user_info['ldap_username']))

assoc = UserAssociation()
assoc.user = user
Expand Down
3 changes: 1 addition & 2 deletions askbot/deps/django_authopenid/middleware.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
# -*- coding: utf-8 -*-
from askbot.deps.django_authopenid import mimeparse
from django.http import HttpResponseRedirect
from django.urls import reverse
import logging

__all__ = ["OpenIDMiddleware"]

class OpenIDMiddleware(object):
class OpenIDMiddleware:
"""
Populate request.openid. This comes either from cookie or from
session, depending on the presence of OPENID_USE_SESSIONS.
Expand Down
11 changes: 5 additions & 6 deletions askbot/deps/django_authopenid/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
import datetime

from django.conf import settings
Expand Down Expand Up @@ -36,7 +35,7 @@ class Association(models.Model):
assoc_type = models.TextField(max_length=64)

def __str__(self):
return "Association: %s, %s" % (self.server_url, self.handle)
return f"Association: {self.server_url}, {self.handle}"

class UserAssociation(models.Model):
"""
Expand All @@ -52,14 +51,14 @@ class UserAssociation(models.Model):
provider_name = models.CharField(max_length=64, default='unknown')
last_used_timestamp = models.DateTimeField(null=True)

class Meta(object):
class Meta:
unique_together = (
('user','provider_name'),
('openid_url', 'provider_name')
)

def __str__(self):
return "Openid %s with user %s" % (self.openid_url, self.user)
return f"Openid {self.openid_url} with user {self.user}"

def update_timestamp(self):
self.last_used_timestamp = datetime.datetime.now()
Expand All @@ -72,7 +71,7 @@ def get_new_confirm_key(self):
# The random module is seeded when this Apache child is created.
# Use SECRET_KEY as added salt.
while 1:
confirm_key = hashlib.md5("%s%s%s%s" % (
confirm_key = hashlib.md5("{}{}{}{}".format(
random.randint(0, sys.maxsize - 1), os.getpid(),
time.time(), settings.SECRET_KEY)).hexdigest()
try:
Expand Down Expand Up @@ -108,7 +107,7 @@ def save(self, *args, **kwargs):
self.expires_on = timezone.now() + \
datetime.timedelta(VERIFIER_EXPIRE_DAYS)

super(UserEmailVerifier, self).save(*args, **kwargs)
super().save(*args, **kwargs)

def has_expired(self):
now = timezone.now()
Expand Down
2 changes: 1 addition & 1 deletion askbot/deps/django_authopenid/protocols/base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class BaseProtocol(object):
class BaseProtocol:
"""Base class for all authentication protocols"""

def __iter__(self):
Expand Down
4 changes: 2 additions & 2 deletions askbot/deps/django_authopenid/protocols/oauth1.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ def send_request(self, client=None, url=None, method='GET', params=None, **kwarg
if parsed_response:
return parsed_response
else:
raise OAuthError('error obtaining request token {0}'.format(content))
raise OAuthError(f'error obtaining request token {content}')
else:
raise OAuthError('response is {0}'.format(response))
raise OAuthError(f'response is {response}')

def get_token(self):
return self.request_token
Expand Down
4 changes: 2 additions & 2 deletions askbot/deps/django_authopenid/providers/discourse.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def get_sso_login_url(request, success_url):
# (where the Discourse will redirect user after verification).
# Payload should look like: nonce=NONCE&return_sso_url=RETURN_URL
return_url = site_url(reverse('user_complete_discourse_signin'))
payload = 'nonce={}&return_sso_url={}'.format(nonce, return_url)
payload = f'nonce={nonce}&return_sso_url={return_url}'
# Base64 encode the above raw payload. -> BASE64_PAYLOAD
base64_payload = base64.b64encode(payload)
# URL encode the above BASE64_PAYLOAD.
Expand All @@ -52,7 +52,7 @@ class DiscourseSsoForm(forms.Form):

def __init__(self, *args, **kwargs):
self.expected_nonce = kwargs.pop('nonce', None)
super(DiscourseSsoForm, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)

def clean(self):
sso = self.cleaned_data['sso']
Expand Down
Loading