From 7db147e06a11307af93139239f35efd60c0ec968 Mon Sep 17 00:00:00 2001 From: Christie Rice <8483753+crice100@users.noreply.github.com> Date: Tue, 9 Feb 2021 10:20:46 -0500 Subject: [PATCH] Fix lint-amnesty warnings (#26412) --- lms/djangoapps/certificates/admin.py | 4 +- lms/djangoapps/certificates/api.py | 9 ++-- .../certificates/apis/v0/permissions.py | 4 +- .../management/commands/cert_whitelist.py | 6 ++- .../management/commands/create_fake_cert.py | 3 +- .../management/commands/gen_cert_report.py | 6 ++- .../management/commands/regenerate_user.py | 5 +- .../commands/resubmit_error_certificates.py | 6 +-- .../management/commands/ungenerated_certs.py | 5 +- lms/djangoapps/certificates/models.py | 35 ++++++------- lms/djangoapps/certificates/queue.py | 10 ++-- lms/djangoapps/certificates/signals.py | 5 +- lms/djangoapps/certificates/tasks.py | 3 +- lms/djangoapps/certificates/views/webview.py | 51 ++++++++++--------- lms/djangoapps/certificates/views/xqueue.py | 24 ++++----- 15 files changed, 97 insertions(+), 79 deletions(-) diff --git a/lms/djangoapps/certificates/admin.py b/lms/djangoapps/certificates/admin.py index e6467e51bc..2a4bad1a1b 100644 --- a/lms/djangoapps/certificates/admin.py +++ b/lms/djangoapps/certificates/admin.py @@ -27,7 +27,7 @@ class CertificateTemplateForm(forms.ModelForm): Django admin form for CertificateTemplate model """ def __init__(self, *args, **kwargs): - super(CertificateTemplateForm, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().__init__(*args, **kwargs) organizations = get_organizations() org_choices = [(org["id"], org["name"]) for org in organizations] org_choices.insert(0, ('', 'None')) @@ -68,7 +68,7 @@ class CertificateTemplateAssetAdmin(admin.ModelAdmin): extra_context = {'title': mark_safe('Select Certificate Template Asset to change

' '
Warning! Updating ' 'stage asset would also update production asset
')} - return super(CertificateTemplateAssetAdmin, self).changelist_view(request, extra_context=extra_context) # lint-amnesty, pylint: disable=super-with-arguments + return super().changelist_view(request, extra_context=extra_context) class GeneratedCertificateAdmin(admin.ModelAdmin): diff --git a/lms/djangoapps/certificates/api.py b/lms/djangoapps/certificates/api.py index f8ae0d7997..f10fa052bb 100644 --- a/lms/djangoapps/certificates/api.py +++ b/lms/djangoapps/certificates/api.py @@ -210,9 +210,9 @@ def certificate_downloadable_status(student, course_key): response_data = { 'is_downloadable': False, - 'is_generating': True if current_status['status'] in [CertificateStatuses.generating, # lint-amnesty, pylint: disable=simplifiable-if-expression + 'is_generating': True if current_status['status'] in [CertificateStatuses.generating, # pylint: disable=simplifiable-if-expression CertificateStatuses.error] else False, - 'is_unverified': True if current_status['status'] == CertificateStatuses.unverified else False, # lint-amnesty, pylint: disable=simplifiable-if-expression + 'is_unverified': True if current_status['status'] == CertificateStatuses.unverified else False, # pylint: disable=simplifiable-if-expression 'download_url': None, 'uuid': None, } @@ -466,7 +466,10 @@ def get_language_specific_template(language, templates): return None -def get_all_languages_or_default_template(templates): # lint-amnesty, pylint: disable=missing-function-docstring +def get_all_languages_or_default_template(templates): + """ + Returns the first template that isn't language specific + """ for template in templates: if template.language == '': return template diff --git a/lms/djangoapps/certificates/apis/v0/permissions.py b/lms/djangoapps/certificates/apis/v0/permissions.py index 588c8b262d..182e1aab6d 100644 --- a/lms/djangoapps/certificates/apis/v0/permissions.py +++ b/lms/djangoapps/certificates/apis/v0/permissions.py @@ -3,11 +3,13 @@ This module provides a custom DRF Permission class for supporting the course cer to Admin users and users whom they belongs to. """ -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from rest_framework.permissions import BasePermission from openedx.core.djangoapps.user_api.models import UserPreference +User = get_user_model() + class IsOwnerOrPublicCertificates(BasePermission): """ diff --git a/lms/djangoapps/certificates/management/commands/cert_whitelist.py b/lms/djangoapps/certificates/management/commands/cert_whitelist.py index a9ed3423c0..331719e3f6 100644 --- a/lms/djangoapps/certificates/management/commands/cert_whitelist.py +++ b/lms/djangoapps/certificates/management/commands/cert_whitelist.py @@ -4,12 +4,14 @@ user/course """ -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from opaque_keys.edx.keys import CourseKey from lms.djangoapps.certificates.models import CertificateWhitelist +User = get_user_model() + def get_user_from_identifier(identifier): """ @@ -98,7 +100,7 @@ class Command(BaseCommand): if options['add'] or options['del']: user_str = options['add'] or options['del'] - add_to_whitelist = True if options['add'] else False # lint-amnesty, pylint: disable=simplifiable-if-expression + add_to_whitelist = True if options['add'] else False # pylint: disable=simplifiable-if-expression users_list = user_str.split(",") for username in users_list: if username.strip(): diff --git a/lms/djangoapps/certificates/management/commands/create_fake_cert.py b/lms/djangoapps/certificates/management/commands/create_fake_cert.py index 7c1506dda8..2ce247b002 100644 --- a/lms/djangoapps/certificates/management/commands/create_fake_cert.py +++ b/lms/djangoapps/certificates/management/commands/create_fake_cert.py @@ -14,7 +14,7 @@ Example usage: import logging from textwrap import dedent -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from opaque_keys.edx.keys import CourseKey from six import text_type @@ -22,6 +22,7 @@ from six import text_type from lms.djangoapps.certificates.models import CertificateStatuses, GeneratedCertificate LOGGER = logging.getLogger(__name__) +User = get_user_model() class Command(BaseCommand): diff --git a/lms/djangoapps/certificates/management/commands/gen_cert_report.py b/lms/djangoapps/certificates/management/commands/gen_cert_report.py index 063de52f47..977a9d9535 100644 --- a/lms/djangoapps/certificates/management/commands/gen_cert_report.py +++ b/lms/djangoapps/certificates/management/commands/gen_cert_report.py @@ -3,7 +3,7 @@ Generate a report of certificate statuses """ -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand, CommandError from django.db.models import Count from opaque_keys.edx.keys import CourseKey @@ -11,6 +11,8 @@ from six import text_type from lms.djangoapps.certificates.models import GeneratedCertificate +User = get_user_model() + class Command(BaseCommand): """ @@ -110,7 +112,7 @@ class Command(BaseCommand): # all states we have seen far all courses status_headings = sorted( - set([status for course in cert_data for status in cert_data[course]]) # lint-amnesty, pylint: disable=consider-using-set-comprehension + set([status for course in cert_data for status in cert_data[course]]) # pylint: disable=consider-using-set-comprehension ) # print the heading for the report diff --git a/lms/djangoapps/certificates/management/commands/regenerate_user.py b/lms/djangoapps/certificates/management/commands/regenerate_user.py index 3b80f03bff..3843728edd 100644 --- a/lms/djangoapps/certificates/management/commands/regenerate_user.py +++ b/lms/djangoapps/certificates/management/commands/regenerate_user.py @@ -4,17 +4,18 @@ import copy import logging -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from opaque_keys.edx.keys import CourseKey from six import text_type +from xmodule.modulestore.django import modulestore from lms.djangoapps.badges.events.course_complete import get_completion_badge from lms.djangoapps.badges.utils import badges_enabled from lms.djangoapps.certificates.api import regenerate_user_certificates -from xmodule.modulestore.django import modulestore LOGGER = logging.getLogger(__name__) +User = get_user_model() class Command(BaseCommand): diff --git a/lms/djangoapps/certificates/management/commands/resubmit_error_certificates.py b/lms/djangoapps/certificates/management/commands/resubmit_error_certificates.py index 37bf08a136..4b5325de02 100644 --- a/lms/djangoapps/certificates/management/commands/resubmit_error_certificates.py +++ b/lms/djangoapps/certificates/management/commands/resubmit_error_certificates.py @@ -64,12 +64,12 @@ class Command(BaseCommand): for course_key_str in options['course_key_list']: try: only_course_keys.append(CourseKey.from_string(course_key_str)) - except InvalidKeyError: - raise CommandError( # lint-amnesty, pylint: disable=raise-missing-from + except InvalidKeyError as e: + raise CommandError( u'"{course_key_str}" is not a valid course key.'.format( course_key_str=course_key_str ) - ) + ) from e if only_course_keys: LOGGER.info( diff --git a/lms/djangoapps/certificates/management/commands/ungenerated_certs.py b/lms/djangoapps/certificates/management/commands/ungenerated_certs.py index 43dff742a2..8b6c83ae7f 100644 --- a/lms/djangoapps/certificates/management/commands/ungenerated_certs.py +++ b/lms/djangoapps/certificates/management/commands/ungenerated_certs.py @@ -7,17 +7,18 @@ courses that have finished, and put their cert requests on the queue. import datetime import logging -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from django.core.management.base import BaseCommand from opaque_keys.edx.keys import CourseKey from pytz import UTC from six import text_type +from xmodule.modulestore.django import modulestore from lms.djangoapps.certificates.api import generate_user_certificates from lms.djangoapps.certificates.models import CertificateStatuses, certificate_status_for_student -from xmodule.modulestore.django import modulestore LOGGER = logging.getLogger(__name__) +User = get_user_model() class Command(BaseCommand): diff --git a/lms/djangoapps/certificates/models.py b/lms/djangoapps/certificates/models.py index 18cdb705ab..6b3dbbc3ec 100644 --- a/lms/djangoapps/certificates/models.py +++ b/lms/djangoapps/certificates/models.py @@ -56,7 +56,7 @@ import six from config_models.models import ConfigurationModel from django.apps import apps from django.conf import settings -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from django.core.exceptions import ValidationError from django.db import models, transaction from django.db.models import Count @@ -69,16 +69,17 @@ from model_utils.models import TimeStampedModel from opaque_keys.edx.django.models import CourseKeyField from simple_history.models import HistoricalRecords +from common.djangoapps.course_modes.models import CourseMode +from common.djangoapps.util.milestones_helpers import fulfill_course_milestone, is_prerequisite_courses_enabled from lms.djangoapps.badges.events.course_complete import course_badge_check from lms.djangoapps.badges.events.course_meta import completion_check, course_group_check -from common.djangoapps.course_modes.models import CourseMode from lms.djangoapps.instructor_task.models import InstructorTask from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.signals.signals import COURSE_CERT_AWARDED, COURSE_CERT_CHANGED, COURSE_CERT_REVOKED from openedx.core.djangoapps.xmodule_django.models import NoneToEmptyManager -from common.djangoapps.util.milestones_helpers import fulfill_course_milestone, is_prerequisite_courses_enabled log = logging.getLogger(__name__) +User = get_user_model() class CertificateStatuses(object): @@ -213,7 +214,7 @@ class EligibleCertificateManager(models.Manager): Return a queryset for `GeneratedCertificate` models, filtering out ineligible certificates. """ - return super(EligibleCertificateManager, self).get_queryset().exclude( # lint-amnesty, pylint: disable=super-with-arguments + return super().get_queryset().exclude( status__in=(CertificateStatuses.audit_passing, CertificateStatuses.audit_notpassing) ) @@ -232,7 +233,7 @@ class EligibleAvailableCertificateManager(EligibleCertificateManager): Return a queryset for `GeneratedCertificate` models, filtering out ineligible certificates and any linked to nonexistent courses. """ - return super(EligibleAvailableCertificateManager, self).get_queryset().extra( # lint-amnesty, pylint: disable=super-with-arguments + return super().get_queryset().extra( tables=['course_overviews_courseoverview'], where=['course_id = course_overviews_courseoverview.id'] ) @@ -248,7 +249,7 @@ class GeneratedCertificate(models.Model): """ # Import here instead of top of file since this module gets imported before # the course_modes app is loaded, resulting in a Django deprecation warning. - from common.djangoapps.course_modes.models import CourseMode # lint-amnesty, pylint: disable=reimported + from common.djangoapps.course_modes.models import CourseMode # pylint: disable=reimported # Only returns eligible certificates. This should be used in # preference to the default `objects` manager in most cases. @@ -273,7 +274,7 @@ class GeneratedCertificate(models.Model): 'executive-education' ) - VERIFIED_CERTS_MODES = [CourseMode.VERIFIED, CourseMode.CREDIT_MODE, CourseMode.MASTERS, CourseMode.EXECUTIVE_EDUCATION] # lint-amnesty, pylint: disable=line-too-long + VERIFIED_CERTS_MODES = [CourseMode.VERIFIED, CourseMode.CREDIT_MODE, CourseMode.MASTERS, CourseMode.EXECUTIVE_EDUCATION] # pylint: disable=line-too-long user = models.ForeignKey(User, on_delete=models.CASCADE) course_id = CourseKeyField(max_length=255, blank=True, default=None) @@ -413,13 +414,13 @@ class GeneratedCertificate(models.Model): """ return self.status == CertificateStatuses.downloadable - def save(self, *args, **kwargs): # lint-amnesty, pylint: disable=signature-differs + def save(self, *args, **kwargs): # pylint: disable=signature-differs """ After the base save() method finishes, fire the COURSE_CERT_AWARDED signal iff we are saving a record of a learner passing the course. As well as the COURSE_CERT_CHANGED for any save event. """ - super(GeneratedCertificate, self).save(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().save(*args, **kwargs) COURSE_CERT_CHANGED.send_robust( sender=self.__class__, user=self.user, @@ -636,7 +637,7 @@ def certificate_status(generated_certificate): """ # Import here instead of top of file since this module gets imported before # the course_modes app is loaded, resulting in a Django deprecation warning. - from common.djangoapps.course_modes.models import CourseMode # lint-amnesty, pylint: disable=redefined-outer-name, reimported + from common.djangoapps.course_modes.models import CourseMode # pylint: disable=redefined-outer-name, reimported if generated_certificate: cert_status = { @@ -721,7 +722,7 @@ class ExampleCertificateSet(TimeStampedModel): """ # Import here instead of top of file since this module gets imported before # the course_modes app is loaded, resulting in a Django deprecation warning. - from common.djangoapps.course_modes.models import CourseMode # lint-amnesty, pylint: disable=redefined-outer-name, reimported + from common.djangoapps.course_modes.models import CourseMode # pylint: disable=redefined-outer-name, reimported cert_set = cls.objects.create(course_key=course_key) ExampleCertificate.objects.bulk_create([ @@ -986,8 +987,8 @@ class CertificateGenerationCourseSetting(TimeStampedModel): help_text=( u"Display estimated time to complete the course, which is equal to the maximum hours of effort per week " u"times the length of the course in weeks. This attribute will only be displayed in a certificate when the " - u"attributes 'Weeks to complete' and 'Max effort' have been provided for the course run and its certificate " # lint-amnesty, pylint: disable=line-too-long - u"template includes Hours of Effort." + u"attributes 'Weeks to complete' and 'Max effort' have been provided for the course run and its " + u"certificate template includes Hours of Effort." ) ) @@ -1096,8 +1097,8 @@ class CertificateHtmlViewConfiguration(ConfigurationModel): """ try: json.loads(self.configuration) - except ValueError: - raise ValidationError('Must be valid JSON string.') # lint-amnesty, pylint: disable=raise-missing-from + except ValueError as e: + raise ValidationError('Must be valid JSON string.') from e @classmethod def get_config(cls): @@ -1222,10 +1223,10 @@ class CertificateTemplateAsset(TimeStampedModel): if self.pk is None: asset_image = self.asset self.asset = None - super(CertificateTemplateAsset, self).save(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().save(*args, **kwargs) self.asset = asset_image - super(CertificateTemplateAsset, self).save(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().save(*args, **kwargs) def __str__(self): return u'%s' % (self.asset.url, ) diff --git a/lms/djangoapps/certificates/queue.py b/lms/djangoapps/certificates/queue.py index bcb236980f..b51d7960f9 100644 --- a/lms/djangoapps/certificates/queue.py +++ b/lms/djangoapps/certificates/queue.py @@ -8,15 +8,17 @@ from uuid import uuid4 import lxml.html import six +from capa.xqueue_interface import XQueueInterface, make_hashkey, make_xheader from django.conf import settings from django.test.client import RequestFactory from django.urls import reverse from django.utils.encoding import python_2_unicode_compatible from lxml.etree import ParserError, XMLSyntaxError from requests.auth import HTTPBasicAuth +from xmodule.modulestore.django import modulestore -from capa.xqueue_interface import XQueueInterface, make_hashkey, make_xheader from common.djangoapps.course_modes.models import CourseMode +from common.djangoapps.student.models import CourseEnrollment, UserProfile from lms.djangoapps.certificates.models import CertificateStatuses as status from lms.djangoapps.certificates.models import ( CertificateWhitelist, @@ -26,8 +28,6 @@ from lms.djangoapps.certificates.models import ( ) from lms.djangoapps.grades.api import CourseGradeFactory from lms.djangoapps.verify_student.services import IDVerificationService -from common.djangoapps.student.models import CourseEnrollment, UserProfile -from xmodule.modulestore.django import modulestore LOGGER = logging.getLogger(__name__) @@ -39,7 +39,7 @@ class XQueueAddToQueueError(Exception): def __init__(self, error_code, error_msg): self.error_code = error_code self.error_msg = error_msg - super(XQueueAddToQueueError, self).__init__(six.text_type(self)) # lint-amnesty, pylint: disable=super-with-arguments + super().__init__(six.text_type(self)) def __str__(self): return ( @@ -332,7 +332,7 @@ class XQueueCertInterface(object): mode_is_verified, generate_pdf ) - cert, created = GeneratedCertificate.objects.get_or_create(user=student, course_id=course_id) # lint-amnesty, pylint: disable=unused-variable + cert, __ = GeneratedCertificate.objects.get_or_create(user=student, course_id=course_id) cert.mode = cert_mode cert.user = student diff --git a/lms/djangoapps/certificates/signals.py b/lms/djangoapps/certificates/signals.py index c9177fd67e..0b451a6d24 100644 --- a/lms/djangoapps/certificates/signals.py +++ b/lms/djangoapps/certificates/signals.py @@ -50,7 +50,10 @@ def _update_cert_settings_on_pacing_change(sender, updated_course_overview, **kw @receiver(post_save, sender=CertificateWhitelist, dispatch_uid="append_certificate_whitelist") -def _listen_for_certificate_whitelist_append(sender, instance, **kwargs): # lint-amnesty, pylint: disable=missing-function-docstring, unused-argument +def _listen_for_certificate_whitelist_append(sender, instance, **kwargs): # pylint: disable=unused-argument + """ + Listen for a user being added to or modified on the whitelist (allowlist) + """ if not auto_certificate_generation_enabled(): return diff --git a/lms/djangoapps/certificates/tasks.py b/lms/djangoapps/certificates/tasks.py index 54cf401099..f91687f701 100644 --- a/lms/djangoapps/certificates/tasks.py +++ b/lms/djangoapps/certificates/tasks.py @@ -6,7 +6,7 @@ from logging import getLogger from celery import shared_task from celery_utils.persist_on_failure import LoggedPersistOnFailureTask -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from edx_django_utils.monitoring import set_code_owner_attribute from opaque_keys.edx.keys import CourseKey @@ -14,6 +14,7 @@ from lms.djangoapps.certificates.generation import generate_allowlist_certificat from lms.djangoapps.verify_student.services import IDVerificationService logger = getLogger(__name__) +User = get_user_model() CERTIFICATE_DELAY_SECONDS = 2 diff --git a/lms/djangoapps/certificates/views/webview.py b/lms/djangoapps/certificates/views/webview.py index 54c8b466db..ac600db9c3 100644 --- a/lms/djangoapps/certificates/views/webview.py +++ b/lms/djangoapps/certificates/views/webview.py @@ -1,4 +1,3 @@ -# lint-amnesty, pylint: disable=bad-option-value """ Certificate HTML webview. """ @@ -8,9 +7,8 @@ import logging from datetime import datetime from uuid import uuid4 -import six import pytz - +import six from django.conf import settings from django.contrib.auth.decorators import login_required from django.http import Http404, HttpResponse @@ -22,10 +20,13 @@ from opaque_keys import InvalidKeyError from opaque_keys.edx.keys import CourseKey from organizations import api as organizations_api -from lms.djangoapps.badges.events.course_complete import get_completion_badge -from lms.djangoapps.badges.utils import badges_enabled from common.djangoapps.edxmako.shortcuts import render_to_response from common.djangoapps.edxmako.template import Template +from common.djangoapps.student.models import LinkedInAddToProfileConfiguration +from common.djangoapps.util.date_utils import strftime_localized +from common.djangoapps.util.views import handle_500 +from lms.djangoapps.badges.events.course_complete import get_completion_badge +from lms.djangoapps.badges.utils import badges_enabled from lms.djangoapps.certificates.api import ( get_active_web_certificate, get_certificate_footer_context, @@ -47,9 +48,6 @@ from openedx.core.djangoapps.certificates.api import certificates_viewable_for_c from openedx.core.djangoapps.lang_pref.api import get_closest_released_language from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from openedx.core.lib.courses import course_image_url -from common.djangoapps.student.models import LinkedInAddToProfileConfiguration -from common.djangoapps.util.date_utils import strftime_localized -from common.djangoapps.util.views import handle_500 log = logging.getLogger(__name__) _ = translation.ugettext @@ -66,17 +64,17 @@ def get_certificate_description(mode, certificate_type, platform_name): if mode == 'honor': # Translators: This text describes the 'Honor' course certificate type. certificate_type_description = _(u"An {cert_type} certificate signifies that a " - u"learner has agreed to abide by the honor code established by {platform_name} " # lint-amnesty, pylint: disable=line-too-long - u"and has completed all of the required tasks for this course under its " - u"guidelines.").format(cert_type=certificate_type, - platform_name=platform_name) + u"learner has agreed to abide by the honor code established by " + u"{platform_name} and has completed all of the required tasks for this course " + u"under its guidelines.").format(cert_type=certificate_type, + platform_name=platform_name) elif mode == 'verified': # Translators: This text describes the 'ID Verified' course certificate type, which is a higher level of # verification offered by edX. This type of verification is useful for professional education/certifications certificate_type_description = _(u"A {cert_type} certificate signifies that a " - u"learner has agreed to abide by the honor code established by {platform_name} " # lint-amnesty, pylint: disable=line-too-long - u"and has completed all of the required tasks for this course under its " - u"guidelines. A {cert_type} certificate also indicates that the " + u"learner has agreed to abide by the honor code established by " + u"{platform_name} and has completed all of the required tasks for this course " + u"under its guidelines. A {cert_type} certificate also indicates that the " u"identity of the learner has been checked and " u"is valid.").format(cert_type=certificate_type, platform_name=platform_name) @@ -224,7 +222,7 @@ def _update_context_with_basic_info(context, course_id, platform_name, configura ) -def _update_course_context(request, context, course, course_key, platform_name): # lint-amnesty, pylint: disable=unused-argument +def _update_course_context(request, context, course, platform_name): """ Updates context dictionary with course info. """ @@ -250,7 +248,7 @@ def _update_course_context(request, context, course, course_key, platform_name): platform_name=platform_name) -def _update_social_context(request, context, course, user, user_certificate, platform_name): # lint-amnesty, pylint: disable=unused-argument +def _update_social_context(request, context, course, user_certificate, platform_name): """ Updates context dictionary with info required for social sharing. """ @@ -356,7 +354,7 @@ def _get_user_certificate(request, user, course_key, course, preview_mode=None): return user_certificate -def _track_certificate_events(request, context, course, user, user_certificate): # lint-amnesty, pylint: disable=unused-argument +def _track_certificate_events(request, course, user, user_certificate): """ Tracks web certificate view related events. """ @@ -437,7 +435,7 @@ def _update_organization_context(context, course): context['organization_logo'] = organization_logo -def unsupported_url(request, user_id, course_id): # lint-amnesty, pylint: disable=unused-argument +def unsupported_url(request, user_id, course_id): # pylint: disable=unused-argument """ This view returns the un-supported url page aimed to let the user aware that url is no longer supported @@ -467,8 +465,8 @@ def render_cert_by_uuid(request, certificate_uuid): status=CertificateStatuses.downloadable ) return render_html_view(request, six.text_type(certificate.course_id), certificate) - except GeneratedCertificate.DoesNotExist: - raise Http404 # lint-amnesty, pylint: disable=raise-missing-from + except GeneratedCertificate.DoesNotExist as e: + raise Http404 from e @handle_500( @@ -576,7 +574,7 @@ def render_html_view(request, course_id, certificate=None): _update_organization_context(context, course) # Append course info - _update_course_context(request, context, course, course_key, platform_name) + _update_course_context(request, context, course, platform_name) # Append course run info from discovery context.update(catalog_data) @@ -585,7 +583,7 @@ def render_html_view(request, course_id, certificate=None): _update_context_with_user_info(context, user, user_certificate) # Append social sharing info - _update_social_context(request, context, course, user, user_certificate, platform_name) + _update_social_context(request, context, course, user_certificate, platform_name) # Append/Override the existing view context values with certificate specific values _update_certificate_context(context, course, user_certificate, platform_name) @@ -601,7 +599,7 @@ def render_html_view(request, course_id, certificate=None): context.update(course.cert_html_view_overrides) # Track certificate view events - _track_certificate_events(request, context, course, user, user_certificate) + _track_certificate_events(request, course, user, user_certificate) # Render the certificate return _render_valid_certificate(request, context, custom_template) @@ -676,7 +674,10 @@ def _render_invalid_certificate(request, course_id, platform_name, configuration return render_to_response(cert_path, context) -def _render_valid_certificate(request, context, custom_template=None): # lint-amnesty, pylint: disable=missing-function-docstring +def _render_valid_certificate(request, context, custom_template=None): + """ + Renders certificate + """ if custom_template: template = Template( custom_template.template, diff --git a/lms/djangoapps/certificates/views/xqueue.py b/lms/djangoapps/certificates/views/xqueue.py index bdb5d7e985..33b67247f2 100644 --- a/lms/djangoapps/certificates/views/xqueue.py +++ b/lms/djangoapps/certificates/views/xqueue.py @@ -6,14 +6,16 @@ Views used by XQueue certificate generation. import json import logging -from django.contrib.auth.models import User # lint-amnesty, pylint: disable=imported-auth-user +from django.contrib.auth import get_user_model from django.db import transaction from django.http import Http404, HttpResponse, HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from opaque_keys.edx.keys import CourseKey +from xmodule.modulestore.django import modulestore -from capa.xqueue_interface import XQUEUE_METRIC_NAME # lint-amnesty, pylint: disable=unused-import +from common.djangoapps.util.json_request import JsonResponse, JsonResponseBadRequest +from common.djangoapps.util.request_rate_limiter import BadRequestRateLimiter from lms.djangoapps.certificates.api import generate_user_certificates from lms.djangoapps.certificates.models import ( CertificateStatuses, @@ -21,11 +23,9 @@ from lms.djangoapps.certificates.models import ( GeneratedCertificate, certificate_status_for_student ) -from common.djangoapps.util.json_request import JsonResponse, JsonResponseBadRequest -from common.djangoapps.util.request_rate_limiter import BadRequestRateLimiter -from xmodule.modulestore.django import modulestore log = logging.getLogger(__name__) +User = get_user_model() # Grades can potentially be written - if so, let grading manage the transaction. @@ -51,8 +51,8 @@ def request_certificate(request): log_msg = u'Grading and certification requested for user %s in course %s via /request_certificate call' log.info(log_msg, username, course_key) status = generate_user_certificates(student, course_key, course=course) - return HttpResponse(json.dumps({'add_status': status}), content_type='application/json') # lint-amnesty, pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps - return HttpResponse(json.dumps({'add_status': 'ERRORANONYMOUSUSER'}), content_type='application/json') # lint-amnesty, pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps + return HttpResponse(json.dumps({'add_status': status}), content_type='application/json') # pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps + return HttpResponse(json.dumps({'add_status': 'ERRORANONYMOUSUSER'}), content_type='application/json') # pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps @csrf_exempt @@ -89,7 +89,7 @@ def update_certificate(request): xqueue_header ) - return HttpResponse(json.dumps({ # lint-amnesty, pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps + return HttpResponse(json.dumps({ # pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps 'return_code': 1, 'content': 'unable to lookup key' }), content_type='application/json') @@ -121,7 +121,7 @@ def update_certificate(request): log.critical( u'Invalid state for cert update: %s', cert.status ) - return HttpResponse( # lint-amnesty, pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps + return HttpResponse( # pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps json.dumps({ 'return_code': 1, 'content': 'invalid cert status' @@ -130,7 +130,7 @@ def update_certificate(request): ) cert.save() - return HttpResponse(json.dumps({'return_code': 0}), # lint-amnesty, pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps + return HttpResponse(json.dumps({'return_code': 0}), # pylint: disable=http-response-with-content-type-json, http-response-with-json-dumps content_type='application/json') @@ -193,14 +193,14 @@ def update_example_certificate(request): uuid = xqueue_body.get('username') access_key = xqueue_header.get('lms_key') cert = ExampleCertificate.objects.get(uuid=uuid, access_key=access_key) - except ExampleCertificate.DoesNotExist: + except ExampleCertificate.DoesNotExist as e: # If we are unable to retrieve the record, it means the uuid or access key # were not valid. This most likely means that the request is NOT coming # from the XQueue. Return a 404 and increase the bad request counter # to protect against a DDOS attack. log.info(u"Could not find example certificate with uuid '%s' and access key '%s'", uuid, access_key) rate_limiter.tick_request_counter(request) - raise Http404 # lint-amnesty, pylint: disable=raise-missing-from + raise Http404 from e if 'error' in xqueue_body: # If an error occurs, save the error message so we can fix the issue.