refactor: pyupgrade second iteration (#27452)

This commit is contained in:
Usama Sadiq
2021-05-10 13:47:33 +05:00
committed by GitHub
parent 8c06b68bbe
commit ea550c06a5
14 changed files with 26 additions and 32 deletions

View File

@@ -1,6 +1,3 @@
# -*- coding: utf-8 -*-
from django.db import migrations, models
# We used to have a uniqueness constraint on auth_user.email:

View File

@@ -16,7 +16,7 @@ LOOKUP = {}
from .paths import add_lookup, clear_lookups, lookup_template, save_lookups # lint-amnesty, pylint: disable=wrong-import-position
class Engines(object):
class Engines:
"""
Aliases for the available template engines.
Note that the preview engine is only configured for cms.

View File

@@ -52,7 +52,7 @@ class MakoLoader:
# In order to allow dynamic template overrides, we need to cache templates based on their absolute paths
# rather than relative paths, overriding templates would have same relative paths.
module_directory = self.module_directory.rstrip("/") + "/{dir_hash}/".format(dir_hash=hash(origin.name))
module_directory = self.module_directory.rstrip("/") + f"/{hash(origin.name)}/"
if source.startswith("## mako\n"):
# This is a mako template

View File

@@ -93,11 +93,11 @@ def marketing_link(name):
try:
return reverse(link_map[name])
except NoReverseMatch:
log.debug(u"Cannot find corresponding link for name: %s", name)
log.debug("Cannot find corresponding link for name: %s", name)
set_custom_attribute('unresolved_marketing_link', name)
return '#'
else:
log.debug(u"Cannot find corresponding link for name: %s", name)
log.debug("Cannot find corresponding link for name: %s", name)
return '#'
@@ -143,15 +143,12 @@ def marketing_link_context_processor(request):
settings.MKTG_URLS
)
return dict( # lint-amnesty, pylint: disable=consider-using-dict-comprehension
[
("MKTG_URL_" + k, marketing_link(k))
for k in (
six.viewkeys(settings.MKTG_URL_LINK_MAP) |
six.viewkeys(marketing_urls)
)
]
)
return {
"MKTG_URL_" + k: marketing_link(k)
for k in (
settings.MKTG_URL_LINK_MAP.keys() | marketing_urls.keys()
)
}
def render_to_string(template_name, dictionary, namespace='main', request=None):

View File

@@ -27,7 +27,7 @@ KEY_CSRF_TOKENS = ('csrf_token', 'csrf')
UNKNOWN_SOURCE = '<unknown source>'
class Template(object):
class Template:
"""
This bridges the gap between a Mako template and a Django template. It can
be rendered like it is a Django template because the arguments are transformed

View File

@@ -34,7 +34,7 @@ class GlobalStatusMessage(ConfigurationModel):
def full_message(self, course_key):
""" Returns the full status message, including any course-specific status messages. """
cache_key = "status_message.{course_id}".format(course_id=str(course_key))
cache_key = f"status_message.{str(course_key)}"
if cache.get(cache_key):
return cache.get(cache_key)

View File

@@ -66,7 +66,7 @@ class Command(TrackedCommand):
mode = enrollment.mode
old_is_active = enrollment.is_active
CourseEnrollment.unenroll(user, source_key, skip_refund=True)
print('Unenrolled {} from {}'.format(user.username, str(source_key)))
print(f'Unenrolled {user.username} from {str(source_key)}')
for dest_key in dest_keys:
if CourseEnrollment.is_enrolled(user, dest_key):

View File

@@ -421,7 +421,7 @@ def get_potentially_retired_user_by_username(username):
# We should have, at most, a retired username and an active one with a username
# differing only by case. If there are more we need to disambiguate them by hand.
raise Exception('Expected 1 or 2 Users, received {}'.format(str(potential_users)))
raise Exception(f'Expected 1 or 2 Users, received {str(potential_users)}')
def get_potentially_retired_user_by_username_and_hash(username, hashed_username):
@@ -898,7 +898,7 @@ class Registration(models.Model):
db_table = "auth_registration"
user = models.OneToOneField(User, on_delete=models.CASCADE)
activation_key = models.CharField((u'activation key'), max_length=32, unique=True, db_index=True)
activation_key = models.CharField(('activation key'), max_length=32, unique=True, db_index=True)
activation_timestamp = models.DateTimeField(default=None, null=True, blank=True)
def register(self, user):
@@ -913,7 +913,7 @@ class Registration(models.Model):
self.activation_timestamp = datetime.utcnow()
self.save()
USER_ACCOUNT_ACTIVATED.send_robust(self.__class__, user=self.user)
log.info(u'User %s (%s) account is successfully activated.', self.user.username, self.user.email)
log.info('User %s (%s) account is successfully activated.', self.user.username, self.user.email)
class PendingNameChange(DeletableByUserValue, models.Model):
@@ -1807,7 +1807,7 @@ class CourseEnrollment(models.Model):
enrollments = [(str(e[0]).lower(), e[1].lower()) for e in enrollments]
enrollments = sorted(enrollments, key=lambda e: e[0])
hash_elements = [user.username]
hash_elements += ['{course_id}={mode}'.format(course_id=e[0], mode=e[1]) for e in enrollments]
hash_elements += [f'{e[0]}={e[1]}' for e in enrollments]
status_hash = hashlib.md5('&'.join(hash_elements).encode('utf-8')).hexdigest()
# The hash is cached indefinitely. It will be invalidated when the user enrolls/unenrolls.

View File

@@ -1,9 +1,9 @@
# lint-amnesty, pylint: disable=missing-module-docstring
import datetime
import hashlib
from unittest import mock
import ddt
import mock
import pytz
from crum import set_current_request
from django.contrib.auth.models import AnonymousUser, User # lint-amnesty, pylint: disable=imported-auth-user
@@ -98,7 +98,7 @@ class CourseEnrollmentTests(SharedModuleStoreTestCase): # lint-amnesty, pylint:
enrollments = CourseEnrollment.enrollments_for_user(self.user).order_by(Lower('course_id'))
hash_elements = [self.user.username]
hash_elements += [
'{course_id}={mode}'.format(course_id=str(enrollment.course_id).lower(), mode=enrollment.mode.lower()) for
f'{str(enrollment.course_id).lower()}={enrollment.mode.lower()}' for
enrollment in enrollments]
expected = hashlib.md5('&'.join(hash_elements).encode('utf-8')).hexdigest()
assert CourseEnrollment.generate_enrollment_status_hash(self.user) == expected

View File

@@ -197,7 +197,7 @@ class RefundableTest(SharedModuleStoreTestCase):
""" Order with mutiple refunds will not throw 500 error when dashboard page will access."""
now = datetime.now(pytz.UTC).replace(microsecond=0)
order_date = now + timedelta(days=1)
expected_content = '{{"date_placed": "{date}"}}'.format(date=order_date.strftime(ECOMMERCE_DATE_FORMAT))
expected_content = f'{{"date_placed": "{order_date.strftime(ECOMMERCE_DATE_FORMAT)}"}}'
httpretty.register_uri(
httpretty.GET,

View File

@@ -388,7 +388,7 @@ class TestCourseVerificationStatus(UrlResetMixin, ModuleStoreTestCase):
# Verify that the correct banner color is rendered
self.assertContains(
response,
"<article class=\"course {}\"".format(self.MODE_CLASSES[status])
f"<article class=\"course {self.MODE_CLASSES[status]}\""
)
# Verify that the correct copy is rendered on the dashboard

View File

@@ -722,7 +722,7 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
ItemFactory.create(
category='video',
parent_location=course.location,
display_name='Video {}'.format(str(number))
display_name=f'Video {str(number)}'
).location
for number in range(5)
]
@@ -823,7 +823,7 @@ class StudentDashboardTests(SharedModuleStoreTestCase, MilestonesTestCaseMixin,
ItemFactory.create(
category='video',
parent_location=course.location,
display_name='Video {}'.format(str(number))
display_name=f'Video {str(number)}'
).location
for number in range(5)
]

View File

@@ -79,7 +79,7 @@ class StubLtiHandler(StubHttpRequestHandler):
'sourcedId': self.post_dict.get('lis_result_sourcedid')
}
host = os.environ.get('BOK_CHOY_HOSTNAME', self.server.server_address[0])
submit_url = '//{}:{}'.format(host, self.server.server_address[1])
submit_url = f'//{host}:{self.server.server_address[1]}'
content = self._create_content(status_message, submit_url)
self.send_response(200, content)
else:

View File

@@ -134,7 +134,7 @@ class StubYouTubeHandler(StubHttpRequestHandler):
})
)
})
response = "{cb}({data})".format(cb=callback, data=json.dumps(data)).encode('utf-8')
response = f"{callback}({json.dumps(data)})".encode('utf-8')
self.send_response(200, content=response, headers={'Content-type': 'text/html'})
self.log_message(f"Youtube: sent response {message}")
@@ -158,7 +158,7 @@ class StubYouTubeHandler(StubHttpRequestHandler):
"message": message,
})
})
response = "{cb}({data})".format(cb=callback, data=json.dumps(data)).encode('utf-8')
response = f"{callback}({json.dumps(data)})".encode('utf-8')
self.send_response(200, content=response, headers={'Content-type': 'text/html'})
self.log_message(f"Youtube: sent response {message}")