From 65f79ef9b3d199ee944eed156f711e1a970cbc10 Mon Sep 17 00:00:00 2001 From: "M. Zulqarnain" Date: Thu, 25 Feb 2021 14:37:09 +0500 Subject: [PATCH] BOM-2365 : pyupgrade on static_templates, staticbook and support apps (#26699) *pyupgrade on static_templates, staticbook and support apps This reverts commit 1ec2e797a1bbc83b4ded77b1edd790bccbf30c6e. * Apply suggestions from code review Co-authored-by: Usama Sadiq --- .../static_template_view/tests/test_views.py | 18 ++--- lms/djangoapps/static_template_view/urls.py | 2 +- lms/djangoapps/static_template_view/views.py | 4 +- lms/djangoapps/staticbook/tests.py | 8 +-- lms/djangoapps/staticbook/views.py | 12 ++-- lms/djangoapps/support/serializers.py | 14 ++-- lms/djangoapps/support/tests/test_views.py | 71 ++++++++++--------- lms/djangoapps/support/urls.py | 2 +- lms/djangoapps/support/views/certificate.py | 3 +- lms/djangoapps/support/views/contact_us.py | 4 +- lms/djangoapps/support/views/enrollments.py | 24 ++++--- lms/djangoapps/support/views/manage_user.py | 5 +- .../support/views/program_enrollments.py | 11 ++- lms/djangoapps/support/views/sso_records.py | 2 +- 14 files changed, 88 insertions(+), 92 deletions(-) diff --git a/lms/djangoapps/static_template_view/tests/test_views.py b/lms/djangoapps/static_template_view/tests/test_views.py index 562ae9e69c..f876c8897b 100644 --- a/lms/djangoapps/static_template_view/tests/test_views.py +++ b/lms/djangoapps/static_template_view/tests/test_views.py @@ -37,10 +37,10 @@ class MarketingSiteViewTests(TestCase): """ Test the about view with the header and content set in SiteConfiguration. """ - test_header = u"Very Unique Test Header" - test_content = u"Very Unique Test Content" - test_header_key = u'static_template_about_header' - test_content_key = u'static_template_about_content' + test_header = "Very Unique Test Header" + test_content = "Very Unique Test Content" + test_header_key = 'static_template_about_header' + test_content_key = 'static_template_about_content' response = None configuration = {test_header_key: test_header, test_content_key: test_content} with with_site_configuration_context(configuration=configuration): @@ -52,10 +52,10 @@ class MarketingSiteViewTests(TestCase): """ Test the about view with html in the header. """ - test_header = u"Very Unique Test Header" - test_content = u"Very Unique Test Content" - test_header_key = u'static_template_about_header' - test_content_key = u'static_template_about_content' + test_header = "Very Unique Test Header" + test_content = "Very Unique Test Content" + test_header_key = 'static_template_about_header' + test_content_key = 'static_template_about_content' response = None configuration = {test_header_key: test_header, test_content_key: test_content} with with_site_configuration_context(configuration=configuration): @@ -85,7 +85,7 @@ class MarketingSiteViewTests(TestCase): resp = self.client.get(url) self.assertContains( resp, - u'There has been a 500 error on the {platform_name} servers'.format( + 'There has been a 500 error on the {platform_name} servers'.format( platform_name=settings.PLATFORM_NAME ), status_code=500 diff --git a/lms/djangoapps/static_template_view/urls.py b/lms/djangoapps/static_template_view/urls.py index 5dd3fa96be..a05783085c 100644 --- a/lms/djangoapps/static_template_view/urls.py +++ b/lms/djangoapps/static_template_view/urls.py @@ -46,7 +46,7 @@ for key, value in settings.MKTG_URL_LINK_MAP.items(): if '.' not in template: # Append STATIC_TEMPLATE_VIEW_DEFAULT_FILE_EXTENSION if # no file extension was specified in the key - template = "%s.%s" % (template, settings.STATIC_TEMPLATE_VIEW_DEFAULT_FILE_EXTENSION) + template = f"{template}.{settings.STATIC_TEMPLATE_VIEW_DEFAULT_FILE_EXTENSION}" # Make the assumption that the URL we want is the lowercased # version of the map key diff --git a/lms/djangoapps/static_template_view/views.py b/lms/djangoapps/static_template_view/views.py index 9ce2666bc2..f63cb58171 100644 --- a/lms/djangoapps/static_template_view/views.py +++ b/lms/djangoapps/static_template_view/views.py @@ -15,13 +15,13 @@ from django.template import TemplateDoesNotExist from django.utils.safestring import mark_safe from django.views.decorators.csrf import ensure_csrf_cookie from django.views.defaults import permission_denied -from ratelimit.exceptions import Ratelimited from mako.exceptions import TopLevelLookupException +from ratelimit.exceptions import Ratelimited from common.djangoapps.edxmako.shortcuts import render_to_response, render_to_string -from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from common.djangoapps.util.cache import cache_if_anonymous from common.djangoapps.util.views import fix_crum_request +from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers valid_templates = [] diff --git a/lms/djangoapps/staticbook/tests.py b/lms/djangoapps/staticbook/tests.py index 56153b42df..f560ddb7e3 100644 --- a/lms/djangoapps/staticbook/tests.py +++ b/lms/djangoapps/staticbook/tests.py @@ -4,11 +4,11 @@ Test the lms/staticbook views. import textwrap +from unittest import mock + import pytest -import mock import requests from django.urls import NoReverseMatch, reverse -from six import text_type from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase @@ -50,7 +50,7 @@ class StaticBookTest(ModuleStoreTestCase): """ def __init__(self, *args, **kwargs): - super(StaticBookTest, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().__init__(*args, **kwargs) self.course = None def make_course(self, **kwargs): @@ -69,7 +69,7 @@ class StaticBookTest(ModuleStoreTestCase): Automatically provides the course id. """ - kwargs['course_id'] = text_type(self.course.id) + kwargs['course_id'] = str(self.course.id) url = reverse(url_name, kwargs=kwargs) return url diff --git a/lms/djangoapps/staticbook/views.py b/lms/djangoapps/staticbook/views.py index 8d0d9a40cd..2e6d1c9a8e 100644 --- a/lms/djangoapps/staticbook/views.py +++ b/lms/djangoapps/staticbook/views.py @@ -8,10 +8,10 @@ from django.http import Http404 from django.views.decorators.clickjacking import xframe_options_exempt from opaque_keys.edx.keys import CourseKey -from lms.djangoapps.courseware.access import has_access -from lms.djangoapps.courseware.courses import get_course_with_access from common.djangoapps.edxmako.shortcuts import render_to_response from common.djangoapps.static_replace import replace_static_urls +from lms.djangoapps.courseware.access import has_access +from lms.djangoapps.courseware.courses import get_course_with_access @login_required @@ -25,7 +25,7 @@ def index(request, course_id, book_index, page=None): book_index = int(book_index) if book_index < 0 or book_index >= len(course.textbooks): - raise Http404(u"Invalid book index value: {0}".format(book_index)) + raise Http404(f"Invalid book index value: {book_index}") textbook = course.textbooks[book_index] table_of_contents = textbook.table_of_contents @@ -83,7 +83,7 @@ def pdf_index(request, course_id, book_index, chapter=None, page=None): book_index = int(book_index) if book_index < 0 or book_index >= len(course.pdf_textbooks): - raise Http404(u"Invalid book index value: {0}".format(book_index)) + raise Http404(f"Invalid book index value: {book_index}") textbook = course.pdf_textbooks[book_index] viewer_params = '&file=' @@ -108,7 +108,7 @@ def pdf_index(request, course_id, book_index, chapter=None, page=None): viewer_params += '#zoom=page-fit&disableRange=true' if page is not None: - viewer_params += '&page={}'.format(page) + viewer_params += f'&page={page}' if request.GET.get('viewer', '') == 'true': template = 'pdf_viewer.html' @@ -151,7 +151,7 @@ def html_index(request, course_id, book_index, chapter=None): book_index = int(book_index) if book_index < 0 or book_index >= len(course.html_textbooks): - raise Http404(u"Invalid book index value: {0}".format(book_index)) + raise Http404(f"Invalid book index value: {book_index}") textbook = course.html_textbooks[book_index] if 'url' in textbook: diff --git a/lms/djangoapps/support/serializers.py b/lms/djangoapps/support/serializers.py index 840df93a36..29baa1f563 100644 --- a/lms/djangoapps/support/serializers.py +++ b/lms/djangoapps/support/serializers.py @@ -4,14 +4,10 @@ Serializers for use in the support app. import json from django.urls import reverse - from rest_framework import serializers from common.djangoapps.student.models import CourseEnrollment, ManualEnrollmentAudit -from lms.djangoapps.program_enrollments.models import ( - ProgramEnrollment, - ProgramCourseEnrollment, -) +from lms.djangoapps.program_enrollments.models import ProgramCourseEnrollment, ProgramEnrollment from openedx.core.djangoapps.catalog.utils import get_programs_by_uuids from openedx.features.course_experience import default_course_url_name @@ -23,7 +19,7 @@ class ManualEnrollmentSerializer(serializers.ModelSerializer): """Serializes a manual enrollment audit object.""" enrolled_by = serializers.SlugRelatedField(slug_field='email', read_only=True, default='') - class Meta(object): + class Meta: model = ManualEnrollmentAudit fields = ('enrolled_by', 'time_stamp', 'reason') @@ -34,7 +30,7 @@ class CourseEnrollmentSerializer(serializers.Serializer): is_active = serializers.BooleanField() mode = serializers.CharField() - class Meta(object): + class Meta: model = CourseEnrollment @@ -47,7 +43,7 @@ class ProgramCourseEnrollmentSerializer(serializers.Serializer): course_enrollment = CourseEnrollmentSerializer() course_url = serializers.SerializerMethodField() - class Meta(object): + class Meta: model = ProgramCourseEnrollment def get_course_url(self, obj): @@ -65,7 +61,7 @@ class ProgramEnrollmentSerializer(serializers.Serializer): program_course_enrollments = ProgramCourseEnrollmentSerializer(many=True) program_name = serializers.SerializerMethodField() - class Meta(object): + class Meta: model = ProgramEnrollment def get_program_name(self, obj): diff --git a/lms/djangoapps/support/tests/test_views.py b/lms/djangoapps/support/tests/test_views.py index adacde150e..5b8cd8895d 100644 --- a/lms/djangoapps/support/tests/test_views.py +++ b/lms/djangoapps/support/tests/test_views.py @@ -1,4 +1,3 @@ -# coding: UTF-8 """ Tests for support views. """ @@ -8,31 +7,35 @@ import itertools import json import re from datetime import datetime, timedelta +from unittest.mock import patch from uuid import UUID, uuid4 import ddt -import six from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.db.models import signals from django.http import HttpResponse from django.urls import reverse -from mock import patch from organizations.tests.factories import OrganizationFactory from pytz import UTC from social_django.models import UserSocialAuth -from common.test.utils import disable_signal from common.djangoapps.course_modes.models import CourseMode from common.djangoapps.course_modes.tests.factories import CourseModeFactory +from common.djangoapps.student.models import ( + ENROLLED_TO_ENROLLED, + CourseEnrollment, + CourseEnrollmentAttribute, + ManualEnrollmentAudit +) +from common.djangoapps.student.roles import GlobalStaff, SupportStaffRole +from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory +from common.djangoapps.third_party_auth.tests.factories import SAMLProviderConfigFactory +from common.test.utils import disable_signal from lms.djangoapps.program_enrollments.tests.factories import ProgramCourseEnrollmentFactory, ProgramEnrollmentFactory from lms.djangoapps.support.serializers import ProgramEnrollmentSerializer from lms.djangoapps.verify_student.models import VerificationDeadline from lms.djangoapps.verify_student.services import IDVerificationService from lms.djangoapps.verify_student.tests.factories import SSOVerificationFactory -from common.djangoapps.student.models import ENROLLED_TO_ENROLLED, CourseEnrollment, CourseEnrollmentAttribute, ManualEnrollmentAudit # lint-amnesty, pylint: disable=line-too-long -from common.djangoapps.student.roles import GlobalStaff, SupportStaffRole -from common.djangoapps.student.tests.factories import CourseEnrollmentFactory, UserFactory -from common.djangoapps.third_party_auth.tests.factories import SAMLProviderConfigFactory from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, SharedModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory @@ -48,7 +51,7 @@ class SupportViewTestCase(ModuleStoreTestCase): def setUp(self): """Create a user and log in. """ - super(SupportViewTestCase, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.user = UserFactory(username=self.USERNAME, email=self.EMAIL, password=self.PASSWORD) self.course = CourseFactory.create() success = self.client.login(username=self.USERNAME, password=self.PASSWORD) @@ -62,7 +65,7 @@ class SupportViewManageUserTests(SupportViewTestCase): def setUp(self): """Make the user support staff""" - super(SupportViewManageUserTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() SupportStaffRole().add_users(self.user) def test_get_contact_us(self): @@ -189,7 +192,7 @@ class SupportViewIndexTests(SupportViewTestCase): def setUp(self): """Make the user support staff. """ - super(SupportViewIndexTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() SupportStaffRole().add_users(self.user) def test_index(self): @@ -207,7 +210,7 @@ class SupportViewCertificatesTests(SupportViewTestCase): """ def setUp(self): """Make the user support staff. """ - super(SupportViewCertificatesTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() SupportStaffRole().add_users(self.user) def test_certificates_no_filter(self): @@ -223,10 +226,10 @@ class SupportViewCertificatesTests(SupportViewTestCase): def test_certificates_along_with_course_filter(self): # Check that an initial filter is passed to the JavaScript client. - url = reverse("support:certificates") + "?user=student@example.com&course_id=" + six.text_type(self.course.id) + url = reverse("support:certificates") + "?user=student@example.com&course_id=" + str(self.course.id) response = self.client.get(url) self.assertContains(response, "userFilter: 'student@example.com'") - self.assertContains(response, "courseFilter: '" + six.text_type(self.course.id) + "'") + self.assertContains(response, "courseFilter: '" + str(self.course.id) + "'") @ddt.ddt @@ -234,10 +237,10 @@ class SupportViewEnrollmentsTests(SharedModuleStoreTestCase, SupportViewTestCase """Tests for the enrollment support view.""" def setUp(self): - super(SupportViewEnrollmentsTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() SupportStaffRole().add_users(self.user) - self.course = CourseFactory(display_name=u'teꜱᴛ') + self.course = CourseFactory(display_name='teꜱᴛ') self.student = UserFactory.create(username='student', email='test@example.com', password='test') for mode in ( @@ -277,7 +280,7 @@ class SupportViewEnrollmentsTests(SharedModuleStoreTestCase, SupportViewTestCase 'mode': CourseMode.AUDIT, 'manual_enrollment': {}, 'user': self.student.username, - 'course_id': six.text_type(self.course.id), + 'course_id': str(self.course.id), 'is_active': True, 'verified_upgrade_deadline': None, }, data[0]) @@ -308,7 +311,7 @@ class SupportViewEnrollmentsTests(SharedModuleStoreTestCase, SupportViewTestCase kwargs={'username_or_email': getattr(self.student, search_string_type)} ) response = self.client.post(url, data={ - 'course_id': six.text_type(self.course.id), + 'course_id': str(self.course.id), 'old_mode': CourseMode.AUDIT, 'new_mode': CourseMode.VERIFIED, 'reason': 'Financial Assistance' @@ -421,11 +424,11 @@ class SupportViewEnrollmentsTests(SharedModuleStoreTestCase, SupportViewTestCase with patch('lms.djangoapps.support.views.enrollments.get_credit_provider_attribute_values') as mock_method: credit_provider = ( - [u'Arizona State University'], 'You are now eligible for credit from Arizona State University' + ['Arizona State University'], 'You are now eligible for credit from Arizona State University' ) mock_method.return_value = credit_provider response = self.client.post(url, data={ - 'course_id': six.text_type(self.course.id), + 'course_id': str(self.course.id), 'old_mode': CourseMode.AUDIT, 'new_mode': new_mode, 'reason': 'Financial Assistance' @@ -436,7 +439,7 @@ class SupportViewEnrollmentsTests(SharedModuleStoreTestCase, SupportViewTestCase self.assert_enrollment(new_mode) if new_mode == 'credit': enrollment_attr = CourseEnrollmentAttribute.objects.first() - assert enrollment_attr.value == six.text_type(credit_provider[0]) + assert enrollment_attr.value == str(credit_provider[0]) def set_course_end_date_and_expiry(self): """ Set the course-end date and expire its verified mode.""" @@ -465,7 +468,7 @@ class SupportViewLinkProgramEnrollmentsTests(SupportViewTestCase): def setUp(self): """Make the user support staff. """ - super(SupportViewLinkProgramEnrollmentsTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.url = reverse("support:link_program_enrollments") SupportStaffRole().add_users(self.user) self.program_uuid = str(uuid4()) @@ -487,7 +490,7 @@ class SupportViewLinkProgramEnrollmentsTests(SupportViewTestCase): Test the view without mocking out the rendering like the rest of the tests. """ response = self.client.get(self.url) - content = six.text_type(response.content, encoding='utf-8') + content = str(response.content, encoding='utf-8') assert '"programUUID": ""' in content assert '"text": ""' in content @@ -497,7 +500,7 @@ class SupportViewLinkProgramEnrollmentsTests(SupportViewTestCase): 'program_uuid': 'notauuid', 'text': self.text, }) - msg = u"Supplied program UUID 'notauuid' is not a valid UUID." + msg = "Supplied program UUID 'notauuid' is not a valid UUID." render_call_dict = mocked_render.call_args[0][1] assert render_call_dict['errors'] == [msg] @@ -510,9 +513,9 @@ class SupportViewLinkProgramEnrollmentsTests(SupportViewTestCase): @ddt.unpack def test_missing_parameter(self, program_uuid, text, mocked_render): error = ( - u"You must provide both a program uuid " - u"and a series of lines with the format " - u"'external_user_key,lms_username'." + "You must provide both a program uuid " + "and a series of lines with the format " + "'external_user_key,lms_username'." ) self.client.post(self.url, data={ 'program_uuid': program_uuid, @@ -548,7 +551,7 @@ class SupportViewLinkProgramEnrollmentsTests(SupportViewTestCase): 'program_uuid': self.program_uuid, 'text': text, }) - msg = u"All linking lines must be in the format 'external_user_key,lms_username'" + msg = "All linking lines must be in the format 'external_user_key,lms_username'" render_call_dict = mocked_render.call_args[0][1] assert render_call_dict['errors'] == [msg] @@ -610,14 +613,14 @@ class SupportViewLinkProgramEnrollmentsTests(SupportViewTestCase): }) render_call_dict = mocked_render.call_args[0][1] if username: - expected_success = "('{}', '{}')".format(external_user_key, username) + expected_success = f"('{external_user_key}', '{username}')" assert render_call_dict['successes'] == [expected_success] program_enrollment.refresh_from_db() assert program_enrollment.user == linked_user program_course_enrollment.refresh_from_db() assert program_course_enrollment.course_enrollment.user == linked_user else: - error = u"All linking lines must be in the format 'external_user_key,lms_username'" + error = "All linking lines must be in the format 'external_user_key,lms_username'" assert render_call_dict['errors'] == [error] @@ -633,7 +636,7 @@ class ProgramEnrollmentsInspectorViewTests(SupportViewTestCase): ) def setUp(self): - super(ProgramEnrollmentsInspectorViewTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.url = reverse("support:program_enrollments_inspector") SupportStaffRole().add_users(self.user) self.program_uuid = str(uuid4()) @@ -659,7 +662,7 @@ class ProgramEnrollmentsInspectorViewTests(SupportViewTestCase): def test_initial_rendering(self): response = self.client.get(self.url) - content = six.text_type(response.content, encoding='utf-8') + content = str(response.content, encoding='utf-8') expected_organization_serialized = '"orgKeys": {}'.format( json.dumps(sorted(self.org_key_list)) ) @@ -681,7 +684,7 @@ class ProgramEnrollmentsInspectorViewTests(SupportViewTestCase): if org_key and external_user_key: user_social_auth = UserSocialAuth.objects.create( user=user, - uid='{0}:{1}'.format(org_key, external_user_key), + uid=f'{org_key}:{external_user_key}', provider='tpa-saml' ) user_info['sso_list'] = [{ @@ -954,7 +957,7 @@ class SsoRecordsTests(SupportViewTestCase): # lint-amnesty, pylint: disable=mis def setUp(self): """Make the user support staff""" - super(SsoRecordsTests, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() SupportStaffRole().add_users(self.user) self.student = UserFactory.create(username='student', email='test@example.com', password='test') self.url = reverse("support:sso_records", kwargs={'username_or_email': self.student.username}) diff --git a/lms/djangoapps/support/urls.py b/lms/djangoapps/support/urls.py index 06554f4c01..ed9c985971 100644 --- a/lms/djangoapps/support/urls.py +++ b/lms/djangoapps/support/urls.py @@ -5,8 +5,8 @@ URLs for the student support app. from django.conf.urls import url -from .views.contact_us import ContactUsView from .views.certificate import CertificatesSupportView +from .views.contact_us import ContactUsView from .views.course_entitlements import EntitlementSupportView from .views.enrollments import EnrollmentSupportListView, EnrollmentSupportView from .views.feature_based_enrollments import FeatureBasedEnrollmentsSupportView diff --git a/lms/djangoapps/support/views/certificate.py b/lms/djangoapps/support/views/certificate.py index 6019551b5e..41e8685d4d 100644 --- a/lms/djangoapps/support/views/certificate.py +++ b/lms/djangoapps/support/views/certificate.py @@ -1,11 +1,10 @@ """ Certificate tool in the student support app. """ - +from urllib.parse import quote_plus, unquote from django.utils.decorators import method_decorator from django.views.generic import View -from six.moves.urllib.parse import quote_plus, unquote from common.djangoapps.edxmako.shortcuts import render_to_response from lms.djangoapps.support.decorators import require_support_permission diff --git a/lms/djangoapps/support/views/contact_us.py b/lms/djangoapps/support/views/contact_us.py index 4612ef4667..180276a400 100644 --- a/lms/djangoapps/support/views/contact_us.py +++ b/lms/djangoapps/support/views/contact_us.py @@ -8,9 +8,9 @@ from django.http import Http404 from django.views.generic import View from common.djangoapps.edxmako.shortcuts import render_to_response +from common.djangoapps.student.models import CourseEnrollment from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.features.enterprise_support import api as enterprise_api -from common.djangoapps.student.models import CourseEnrollment class ContactUsView(View): @@ -35,7 +35,7 @@ class ContactUsView(View): current_site_name = configuration_helpers.get_value("SITE_NAME") if current_site_name: current_site_name = current_site_name.replace(".", "_") - tags.append("site_name_{site}".format(site=current_site_name)) + tags.append(f"site_name_{current_site_name}") if request.user.is_authenticated: context['course_id'] = request.session.get('course_id', '') diff --git a/lms/djangoapps/support/views/enrollments.py b/lms/djangoapps/support/views/enrollments.py index 4a3c43039b..8e2af1072e 100644 --- a/lms/djangoapps/support/views/enrollments.py +++ b/lms/djangoapps/support/views/enrollments.py @@ -2,8 +2,6 @@ Support tool for changing course enrollments. """ - -import six from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user from django.db import transaction from django.db.models import Q @@ -14,10 +12,16 @@ from django.views.generic import View from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from rest_framework.generics import GenericAPIView -from six import text_type from common.djangoapps.course_modes.models import CourseMode from common.djangoapps.edxmako.shortcuts import render_to_response +from common.djangoapps.student.models import ( + ENROLLED_TO_ENROLLED, + CourseEnrollment, + CourseEnrollmentAttribute, + ManualEnrollmentAudit +) +from common.djangoapps.util.json_request import JsonResponse from lms.djangoapps.support.decorators import require_support_permission from lms.djangoapps.support.serializers import ManualEnrollmentSerializer from lms.djangoapps.verify_student.models import VerificationDeadline @@ -25,8 +29,6 @@ from openedx.core.djangoapps.credit.email_utils import get_credit_provider_attri from openedx.core.djangoapps.enrollments.api import get_enrollments, update_enrollment from openedx.core.djangoapps.enrollments.errors import CourseModeNotFoundError from openedx.core.djangoapps.enrollments.serializers import ModeSerializer -from common.djangoapps.student.models import ENROLLED_TO_ENROLLED, CourseEnrollment, CourseEnrollmentAttribute, ManualEnrollmentAudit # lint-amnesty, pylint: disable=line-too-long -from common.djangoapps.util.json_request import JsonResponse class EnrollmentSupportView(View): @@ -91,19 +93,19 @@ class EnrollmentSupportListView(GenericAPIView): reason = request.data['reason'] enrollment = CourseEnrollment.objects.get(user=user, course_id=course_key) if enrollment.mode != old_mode: - return HttpResponseBadRequest(u'User {username} is not enrolled with mode {old_mode}.'.format( + return HttpResponseBadRequest('User {username} is not enrolled with mode {old_mode}.'.format( username=user.username, old_mode=old_mode )) except KeyError as err: - return HttpResponseBadRequest(u'The field {} is required.'.format(text_type(err))) + return HttpResponseBadRequest('The field {} is required.'.format(str(err))) except InvalidKeyError: - return HttpResponseBadRequest(u'Could not parse course key.') + return HttpResponseBadRequest('Could not parse course key.') except (CourseEnrollment.DoesNotExist, User.DoesNotExist): return HttpResponseBadRequest( - u'Could not find enrollment for user {username} in course {course}.'.format( + 'Could not find enrollment for user {username} in course {course}.'.format( username=username_or_email, - course=six.text_type(course_key) + course=str(course_key) ) ) try: @@ -130,7 +132,7 @@ class EnrollmentSupportListView(GenericAPIView): ) return JsonResponse(ManualEnrollmentSerializer(instance=manual_enrollment).data) except CourseModeNotFoundError as err: - return HttpResponseBadRequest(text_type(err)) + return HttpResponseBadRequest(str(err)) @staticmethod def include_verified_mode_info(enrollment_data, course_key): diff --git a/lms/djangoapps/support/views/manage_user.py b/lms/djangoapps/support/views/manage_user.py index 21442a2566..ef83bf518d 100644 --- a/lms/djangoapps/support/views/manage_user.py +++ b/lms/djangoapps/support/views/manage_user.py @@ -11,13 +11,12 @@ from django.utils.translation import ugettext as _ from django.views.generic import View from rest_framework.generics import GenericAPIView -from common.djangoapps.student.models import UserPasswordToggleHistory from common.djangoapps.edxmako.shortcuts import render_to_response +from common.djangoapps.student.models import UserPasswordToggleHistory +from common.djangoapps.util.json_request import JsonResponse from lms.djangoapps.support.decorators import require_support_permission from openedx.core.djangoapps.user_api.accounts.serializers import AccountUserSerializer from openedx.core.djangoapps.user_authn.utils import generate_password -from common.djangoapps.util.json_request import JsonResponse - from openedx.core.djangolib.oauth2_retirement_utils import retire_dot_oauth2_models diff --git a/lms/djangoapps/support/views/program_enrollments.py b/lms/djangoapps/support/views/program_enrollments.py index c0454abc99..a756361551 100644 --- a/lms/djangoapps/support/views/program_enrollments.py +++ b/lms/djangoapps/support/views/program_enrollments.py @@ -13,6 +13,7 @@ from django.views.generic import View from social_django.models import UserSocialAuth from common.djangoapps.edxmako.shortcuts import render_to_response +from common.djangoapps.third_party_auth.models import SAMLProviderConfig from lms.djangoapps.program_enrollments.api import ( fetch_program_enrollments_by_student, get_users_by_external_keys_and_org_key, @@ -24,12 +25,8 @@ from lms.djangoapps.program_enrollments.exceptions import ( ProviderDoesNotExistException ) from lms.djangoapps.support.decorators import require_support_permission -from lms.djangoapps.support.serializers import ( - ProgramEnrollmentSerializer, - serialize_user_info -) +from lms.djangoapps.support.serializers import ProgramEnrollmentSerializer, serialize_user_info from lms.djangoapps.verify_student.services import IDVerificationService -from common.djangoapps.third_party_auth.models import SAMLProviderConfig TEMPLATE_PATH = 'support/link_program_enrollments.html' DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%S' @@ -94,7 +91,7 @@ class LinkProgramEnrollmentSupportView(View): program_uuid = UUID(program_uuid_string) except ValueError: return [], [ - "Supplied program UUID '{}' is not a valid UUID.".format(program_uuid_string) + f"Supplied program UUID '{program_uuid_string}' is not a valid UUID." ] reader = csv.DictReader( linkage_text.splitlines(), fieldnames=('external_key', 'username') @@ -213,7 +210,7 @@ class ProgramEnrollmentsInspectorView(View): result['id_verification'] = IDVerificationService.user_status(user) return result, '' except User.DoesNotExist: - return {}, 'Could not find edx account with {}'.format(username_or_email) + return {}, f'Could not find edx account with {username_or_email}' def _get_external_user_info(self, external_user_key, org_key, idp_provider=None): """ diff --git a/lms/djangoapps/support/views/sso_records.py b/lms/djangoapps/support/views/sso_records.py index 00be03e6db..b86984aac7 100644 --- a/lms/djangoapps/support/views/sso_records.py +++ b/lms/djangoapps/support/views/sso_records.py @@ -8,9 +8,9 @@ from django.utils.decorators import method_decorator from rest_framework.generics import GenericAPIView from social_django.models import UserSocialAuth +from common.djangoapps.util.json_request import JsonResponse from lms.djangoapps.support.decorators import require_support_permission from lms.djangoapps.support.serializers import serialize_sso_records -from common.djangoapps.util.json_request import JsonResponse class SsoView(GenericAPIView):