From 8ca33082ff2278d2e131e478d2cc655eed1ebd0f Mon Sep 17 00:00:00 2001 From: Usama Sadiq <usama.sadiq@arbisoft.com> Date: Thu, 18 Mar 2021 18:37:59 +0500 Subject: [PATCH] refactor: Ran pyupgrade on openedx/core/djangoapps/django_comment_common (#26910) --- .../comment_client/comment.py | 14 ++++---- .../comment_client/commentable.py | 2 +- .../comment_client/models.py | 20 +++++------ .../comment_client/thread.py | 24 ++++++------- .../comment_client/user.py | 36 +++++++++---------- .../comment_client/utils.py | 23 ++++++------ .../migrations/0001_initial.py | 3 -- .../migrations/0002_forumsconfig.py | 3 -- .../migrations/0003_enable_forums.py | 3 -- .../migrations/0004_auto_20161117_1209.py | 5 +-- .../0005_coursediscussionsettings.py | 3 -- ...sediscussionsettings_discussions_id_map.py | 3 +- .../migrations/0007_discussionsidmapping.py | 3 +- .../migrations/0008_role_user_index.py | 3 -- .../django_comment_common/models.py | 23 ++++++------ .../djangoapps/django_comment_common/tests.py | 12 +++---- .../djangoapps/django_comment_common/utils.py | 9 +++-- 17 files changed, 81 insertions(+), 108 deletions(-) diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/comment.py b/openedx/core/djangoapps/django_comment_common/comment_client/comment.py index 6c076d9dce9..ef3e72d04d0 100644 --- a/openedx/core/djangoapps/django_comment_common/comment_client/comment.py +++ b/openedx/core/djangoapps/django_comment_common/comment_client/comment.py @@ -26,11 +26,11 @@ class Comment(models.Model): metrics_tag_fields = ['course_id', 'endorsed', 'closed'] - base_url = "{prefix}/comments".format(prefix=settings.PREFIX) + base_url = f"{settings.PREFIX}/comments" type = 'comment' def __init__(self, *args, **kwargs): - super(Comment, self).__init__(*args, **kwargs) # lint-amnesty, pylint: disable=super-with-arguments + super().__init__(*args, **kwargs) self._cached_thread = None @property @@ -58,7 +58,7 @@ class Comment(models.Model): if action in ['post']: return cls.url_for_comments(params) else: - return super(Comment, cls).url(action, params) + return super().url(action, params) def flagAbuse(self, user, voteable): if voteable.type == 'thread': @@ -100,16 +100,16 @@ class Comment(models.Model): def _url_for_thread_comments(thread_id): - return "{prefix}/threads/{thread_id}/comments".format(prefix=settings.PREFIX, thread_id=thread_id) + return f"{settings.PREFIX}/threads/{thread_id}/comments" def _url_for_comment(comment_id): - return "{prefix}/comments/{comment_id}".format(prefix=settings.PREFIX, comment_id=comment_id) + return f"{settings.PREFIX}/comments/{comment_id}" def _url_for_flag_abuse_comment(comment_id): - return "{prefix}/comments/{comment_id}/abuse_flag".format(prefix=settings.PREFIX, comment_id=comment_id) + return f"{settings.PREFIX}/comments/{comment_id}/abuse_flag" def _url_for_unflag_abuse_comment(comment_id): - return "{prefix}/comments/{comment_id}/abuse_unflag".format(prefix=settings.PREFIX, comment_id=comment_id) + return f"{settings.PREFIX}/comments/{comment_id}/abuse_unflag" diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/commentable.py b/openedx/core/djangoapps/django_comment_common/comment_client/commentable.py index 4c260d7bde9..522144396bb 100644 --- a/openedx/core/djangoapps/django_comment_common/comment_client/commentable.py +++ b/openedx/core/djangoapps/django_comment_common/comment_client/commentable.py @@ -9,7 +9,7 @@ class Commentable(models.Model): accessible_fields = ['id', 'commentable_id'] - base_url = "{prefix}/commentables".format(prefix=settings.PREFIX) + base_url = f"{settings.PREFIX}/commentables" type = 'commentable' def retrieve(self, *args, **kwargs): diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/models.py b/openedx/core/djangoapps/django_comment_common/comment_client/models.py index 8eded633ba1..ed4a65b6f2c 100644 --- a/openedx/core/djangoapps/django_comment_common/comment_client/models.py +++ b/openedx/core/djangoapps/django_comment_common/comment_client/models.py @@ -8,7 +8,7 @@ from .utils import CommentClientRequestError, extract, perform_request log = logging.getLogger(__name__) -class Model(object): +class Model: accessible_fields = ['id'] updatable_fields = ['id'] @@ -32,24 +32,24 @@ class Model(object): return self.attributes[name] except KeyError: if self.retrieved or self.id is None: - raise AttributeError(u"Field {0} does not exist".format(name)) # lint-amnesty, pylint: disable=raise-missing-from + raise AttributeError(f"Field {name} does not exist") # lint-amnesty, pylint: disable=raise-missing-from self.retrieve() return self.__getattr__(name) def __setattr__(self, name, value): if name == 'attributes' or name not in self.accessible_fields + self.updatable_fields: - super(Model, self).__setattr__(name, value) # lint-amnesty, pylint: disable=super-with-arguments + super().__setattr__(name, value) else: self.attributes[name] = value def __getitem__(self, key): if key not in self.accessible_fields: - raise KeyError(u"Field {0} does not exist".format(key)) + raise KeyError(f"Field {key} does not exist") return self.attributes.get(key) def __setitem__(self, key, value): if key not in self.accessible_fields + self.updatable_fields: - raise KeyError(u"Field {0} does not exist".format(key)) + raise KeyError(f"Field {key} does not exist") self.attributes.__setitem__(key, value) def items(self, *args, **kwargs): @@ -89,11 +89,11 @@ class Model(object): record the class name of the model. """ tags = [ - u'{}.{}:{}'.format(self.__class__.__name__, attr, self[attr]) + '{}.{}:{}'.format(self.__class__.__name__, attr, self[attr]) for attr in self.metric_tag_fields if attr in self.attributes ] - tags.append(u'model_class:{}'.format(self.__class__.__name__)) + tags.append(f'model_class:{self.__class__.__name__}') return tags @classmethod @@ -106,7 +106,7 @@ class Model(object): self.__setattr__(k, v) else: log.warning( - u"Unexpected field {field_name} in model {model_name}".format( + "Unexpected field {field_name} in model {model_name}".format( field_name=k, model_name=self.__class__.__name__ ) @@ -180,12 +180,12 @@ class Model(object): raise CommentClientRequestError("Must provide base_url when using default url function") if action not in cls.DEFAULT_ACTIONS: # lint-amnesty, pylint: disable=no-else-raise raise ValueError( - u"Invalid action {0}. The supported action must be in {1}".format(action, str(cls.DEFAULT_ACTIONS)) + "Invalid action {}. The supported action must be in {}".format(action, str(cls.DEFAULT_ACTIONS)) ) elif action in cls.DEFAULT_ACTIONS_WITH_ID: try: return cls.url_with_id(params) except KeyError: - raise CommentClientRequestError(u"Cannot perform action {0} without id".format(action)) # lint-amnesty, pylint: disable=raise-missing-from + raise CommentClientRequestError(f"Cannot perform action {action} without id") # lint-amnesty, pylint: disable=raise-missing-from else: # action must be in DEFAULT_ACTIONS_WITHOUT_ID now return cls.url_without_id() diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/thread.py b/openedx/core/djangoapps/django_comment_common/comment_client/thread.py index 09a09e26d1f..0bb3378fcf6 100644 --- a/openedx/core/djangoapps/django_comment_common/comment_client/thread.py +++ b/openedx/core/djangoapps/django_comment_common/comment_client/thread.py @@ -39,7 +39,7 @@ class Thread(models.Model): # initializable_fields are sent in POST requests initializable_fields = updatable_fields + ['thread_type', 'context'] - base_url = "{prefix}/threads".format(prefix=settings.PREFIX) + base_url = f"{settings.PREFIX}/threads" default_retrieve_params = {'recursive': False} type = 'thread' @@ -69,7 +69,7 @@ class Thread(models.Model): 'get', url, params, - metric_tags=[u'course_id:{}'.format(query_params['course_id'])], + metric_tags=['course_id:{}'.format(query_params['course_id'])], metric_action='thread.search', paged_results=True ) @@ -93,8 +93,8 @@ class Thread(models.Model): } ) log.info( - u'forum_text_search query="{search_query}" corrected_text="{corrected_text}" course_id={course_id} ' - u'group_id={group_id} page={requested_page} total_results={total_results}'.format( + 'forum_text_search query="{search_query}" corrected_text="{corrected_text}" course_id={course_id} ' + 'group_id={group_id} page={requested_page} total_results={total_results}'.format( search_query=search_query, corrected_text=corrected_text, course_id=course_id, @@ -115,16 +115,16 @@ class Thread(models.Model): @classmethod def url_for_threads(cls, params=None): if params and params.get('commentable_id'): - return u"{prefix}/{commentable_id}/threads".format( + return "{prefix}/{commentable_id}/threads".format( prefix=settings.PREFIX, commentable_id=params['commentable_id'], ) else: - return u"{prefix}/threads".format(prefix=settings.PREFIX) + return f"{settings.PREFIX}/threads" @classmethod def url_for_search_threads(cls): - return "{prefix}/search/threads".format(prefix=settings.PREFIX) + return f"{settings.PREFIX}/search/threads" @classmethod def url(cls, action, params=None): @@ -135,7 +135,7 @@ class Thread(models.Model): elif action == 'search': return cls.url_for_search_threads() else: - return super(Thread, cls).url(action, params) + return super().url(action, params) # TODO: This is currently overriding Model._retrieve only to add parameters # for the request. Model._retrieve should be modified to handle this such @@ -221,16 +221,16 @@ class Thread(models.Model): def _url_for_flag_abuse_thread(thread_id): - return "{prefix}/threads/{thread_id}/abuse_flag".format(prefix=settings.PREFIX, thread_id=thread_id) + return f"{settings.PREFIX}/threads/{thread_id}/abuse_flag" def _url_for_unflag_abuse_thread(thread_id): - return "{prefix}/threads/{thread_id}/abuse_unflag".format(prefix=settings.PREFIX, thread_id=thread_id) + return f"{settings.PREFIX}/threads/{thread_id}/abuse_unflag" def _url_for_pin_thread(thread_id): - return "{prefix}/threads/{thread_id}/pin".format(prefix=settings.PREFIX, thread_id=thread_id) + return f"{settings.PREFIX}/threads/{thread_id}/pin" def _url_for_un_pin_thread(thread_id): - return "{prefix}/threads/{thread_id}/unpin".format(prefix=settings.PREFIX, thread_id=thread_id) + return f"{settings.PREFIX}/threads/{thread_id}/unpin" diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/user.py b/openedx/core/djangoapps/django_comment_common/comment_client/user.py index ba7b635075a..684469c9e78 100644 --- a/openedx/core/djangoapps/django_comment_common/comment_client/user.py +++ b/openedx/core/djangoapps/django_comment_common/comment_client/user.py @@ -2,8 +2,6 @@ """ User model wrapper for comment service""" -from six import text_type - from . import models, settings, utils @@ -22,7 +20,7 @@ class User(models.Model): metric_tag_fields = ['course_id'] - base_url = "{prefix}/users".format(prefix=settings.PREFIX) + base_url = f"{settings.PREFIX}/users" default_retrieve_params = {'complete': True} type = 'user' @@ -42,7 +40,7 @@ class User(models.Model): _url_for_read(self.id), params, metric_action='user.read', - metric_tags=self._metric_tags + ['target.type:{}'.format(source.type)], + metric_tags=self._metric_tags + [f'target.type:{source.type}'], ) def follow(self, source): @@ -52,7 +50,7 @@ class User(models.Model): _url_for_subscription(self.id), params, metric_action='user.follow', - metric_tags=self._metric_tags + ['target.type:{}'.format(source.type)], + metric_tags=self._metric_tags + [f'target.type:{source.type}'], ) def unfollow(self, source): @@ -62,7 +60,7 @@ class User(models.Model): _url_for_subscription(self.id), params, metric_action='user.unfollow', - metric_tags=self._metric_tags + ['target.type:{}'.format(source.type)], + metric_tags=self._metric_tags + [f'target.type:{source.type}'], ) def vote(self, voteable, value): @@ -78,7 +76,7 @@ class User(models.Model): url, params, metric_action='user.vote', - metric_tags=self._metric_tags + ['target.type:{}'.format(voteable.type)], + metric_tags=self._metric_tags + [f'target.type:{voteable.type}'], ) voteable._update_from_response(response) @@ -95,7 +93,7 @@ class User(models.Model): url, params, metric_action='user.unvote', - metric_tags=self._metric_tags + ['target.type:{}'.format(voteable.type)], + metric_tags=self._metric_tags + [f'target.type:{voteable.type}'], ) voteable._update_from_response(response) @@ -105,7 +103,7 @@ class User(models.Model): if not self.course_id: raise utils.CommentClientRequestError("Must provide course_id when retrieving active threads for the user") url = _url_for_user_active_threads(self.id) - params = {'course_id': text_type(self.course_id)} + params = {'course_id': str(self.course_id)} params.update(query_params) response = utils.perform_request( 'get', @@ -125,7 +123,7 @@ class User(models.Model): "Must provide course_id when retrieving subscribed threads for the user", ) url = _url_for_user_subscribed_threads(self.id) - params = {'course_id': text_type(self.course_id)} + params = {'course_id': str(self.course_id)} params.update(query_params) response = utils.perform_request( 'get', @@ -147,7 +145,7 @@ class User(models.Model): retrieve_params = self.default_retrieve_params.copy() retrieve_params.update(kwargs) if self.attributes.get('course_id'): - retrieve_params['course_id'] = text_type(self.course_id) + retrieve_params['course_id'] = str(self.course_id) if self.attributes.get('group_id'): retrieve_params['group_id'] = self.group_id try: @@ -200,41 +198,41 @@ class User(models.Model): def _url_for_vote_comment(comment_id): - return "{prefix}/comments/{comment_id}/votes".format(prefix=settings.PREFIX, comment_id=comment_id) + return f"{settings.PREFIX}/comments/{comment_id}/votes" def _url_for_vote_thread(thread_id): - return "{prefix}/threads/{thread_id}/votes".format(prefix=settings.PREFIX, thread_id=thread_id) + return f"{settings.PREFIX}/threads/{thread_id}/votes" def _url_for_subscription(user_id): - return "{prefix}/users/{user_id}/subscriptions".format(prefix=settings.PREFIX, user_id=user_id) + return f"{settings.PREFIX}/users/{user_id}/subscriptions" def _url_for_user_active_threads(user_id): - return "{prefix}/users/{user_id}/active_threads".format(prefix=settings.PREFIX, user_id=user_id) + return f"{settings.PREFIX}/users/{user_id}/active_threads" def _url_for_user_subscribed_threads(user_id): - return "{prefix}/users/{user_id}/subscribed_threads".format(prefix=settings.PREFIX, user_id=user_id) + return f"{settings.PREFIX}/users/{user_id}/subscribed_threads" def _url_for_read(user_id): """ Returns cs_comments_service url endpoint to mark thread as read for given user_id """ - return "{prefix}/users/{user_id}/read".format(prefix=settings.PREFIX, user_id=user_id) + return f"{settings.PREFIX}/users/{user_id}/read" def _url_for_retire(user_id): """ Returns cs_comments_service url endpoint to retire a user (remove all post content, etc.) """ - return "{prefix}/users/{user_id}/retire".format(prefix=settings.PREFIX, user_id=user_id) + return f"{settings.PREFIX}/users/{user_id}/retire" def _url_for_username_replacement(user_id): """ Returns cs_comments_servuce url endpoint to replace the username of a user """ - return "{prefix}/users/{user_id}/replace_username".format(prefix=settings.PREFIX, user_id=user_id) + return f"{settings.PREFIX}/users/{user_id}/replace_username" diff --git a/openedx/core/djangoapps/django_comment_common/comment_client/utils.py b/openedx/core/djangoapps/django_comment_common/comment_client/utils.py index de38ad12af1..5c052060675 100644 --- a/openedx/core/djangoapps/django_comment_common/comment_client/utils.py +++ b/openedx/core/djangoapps/django_comment_common/comment_client/utils.py @@ -6,7 +6,6 @@ import logging from uuid import uuid4 import requests -import six from django.utils.translation import get_language from .settings import SERVICE_HOST as COMMENTS_SERVICE @@ -15,13 +14,13 @@ log = logging.getLogger(__name__) def strip_none(dic): - return dict([(k, v) for k, v in six.iteritems(dic) if v is not None]) # lint-amnesty, pylint: disable=consider-using-dict-comprehension + return {k: v for k, v in dic.items() if v is not None} # lint-amnesty, pylint: disable=consider-using-dict-comprehension def strip_blank(dic): def _is_blank(v): return isinstance(v, str) and len(v.strip()) == 0 - return dict([(k, v) for k, v in six.iteritems(dic) if not _is_blank(v)]) # lint-amnesty, pylint: disable=consider-using-dict-comprehension + return {k: v for k, v in dic.items() if not _is_blank(v)} # lint-amnesty, pylint: disable=consider-using-dict-comprehension def extract(dic, keys): @@ -43,9 +42,9 @@ def perform_request(method, url, data_or_params=None, raw=False, if metric_tags is None: metric_tags = [] - metric_tags.append(u'method:{}'.format(method)) + metric_tags.append(f'method:{method}') if metric_action: - metric_tags.append(u'action:{}'.format(metric_action)) + metric_tags.append(f'action:{metric_action}') if data_or_params is None: data_or_params = {} @@ -72,12 +71,12 @@ def perform_request(method, url, data_or_params=None, raw=False, timeout=config.connection_timeout ) - metric_tags.append(u'status_code:{}'.format(response.status_code)) + metric_tags.append(f'status_code:{response.status_code}') status_code = int(response.status_code) if status_code > 200: - metric_tags.append(u'result:failure') + metric_tags.append('result:failure') else: - metric_tags.append(u'result:success') + metric_tags.append('result:success') if 200 < status_code < 500: # lint-amnesty, pylint: disable=no-else-raise raise CommentClientRequestError(response.text, response.status_code) @@ -94,7 +93,7 @@ def perform_request(method, url, data_or_params=None, raw=False, data = response.json() except ValueError: raise CommentClientError( # lint-amnesty, pylint: disable=raise-missing-from - u"Invalid JSON response for request {request_id}; first 100 characters: '{content}'".format( + "Invalid JSON response for request {request_id}; first 100 characters: '{content}'".format( request_id=request_id, content=response.text[:100] ) @@ -108,7 +107,7 @@ class CommentClientError(Exception): class CommentClientRequestError(CommentClientError): def __init__(self, msg, status_codes=400): - super(CommentClientRequestError, self).__init__(msg) # lint-amnesty, pylint: disable=super-with-arguments + super().__init__(msg) self.status_code = status_codes @@ -120,7 +119,7 @@ class CommentClientMaintenanceError(CommentClientError): pass -class CommentClientPaginatedResult(object): +class CommentClientPaginatedResult: """ class for paginated results returned from comment services""" def __init__(self, collection, page, num_pages, thread_count=0, corrected_text=None): @@ -155,4 +154,4 @@ def check_forum_heartbeat(): else: return 'forum', False, res.get('check', 'Forum heartbeat failed') except Exception as fail: - return 'forum', False, six.text_type(fail) + return 'forum', False, str(fail) diff --git a/openedx/core/djangoapps/django_comment_common/migrations/0001_initial.py b/openedx/core/djangoapps/django_comment_common/migrations/0001_initial.py index c244ef888d4..c4254b22d04 100644 --- a/openedx/core/djangoapps/django_comment_common/migrations/0001_initial.py +++ b/openedx/core/djangoapps/django_comment_common/migrations/0001_initial.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - from django.conf import settings from django.db import migrations, models from opaque_keys.edx.django.models import CourseKeyField diff --git a/openedx/core/djangoapps/django_comment_common/migrations/0002_forumsconfig.py b/openedx/core/djangoapps/django_comment_common/migrations/0002_forumsconfig.py index bcb80f7c767..d9e0eda4028 100644 --- a/openedx/core/djangoapps/django_comment_common/migrations/0002_forumsconfig.py +++ b/openedx/core/djangoapps/django_comment_common/migrations/0002_forumsconfig.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - import django.db.models.deletion from django.conf import settings from django.db import migrations, models diff --git a/openedx/core/djangoapps/django_comment_common/migrations/0003_enable_forums.py b/openedx/core/djangoapps/django_comment_common/migrations/0003_enable_forums.py index 52fd96da28c..2ee98367da0 100644 --- a/openedx/core/djangoapps/django_comment_common/migrations/0003_enable_forums.py +++ b/openedx/core/djangoapps/django_comment_common/migrations/0003_enable_forums.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - from django.db import migrations, models diff --git a/openedx/core/djangoapps/django_comment_common/migrations/0004_auto_20161117_1209.py b/openedx/core/djangoapps/django_comment_common/migrations/0004_auto_20161117_1209.py index fe7b587b298..07c75da2769 100644 --- a/openedx/core/djangoapps/django_comment_common/migrations/0004_auto_20161117_1209.py +++ b/openedx/core/djangoapps/django_comment_common/migrations/0004_auto_20161117_1209.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - from django.db import migrations, models @@ -14,6 +11,6 @@ class Migration(migrations.Migration): migrations.AlterField( model_name='forumsconfig', name='connection_timeout', - field=models.FloatField(default=5.0, help_text=u'Seconds to wait when trying to connect to the comment service.'), + field=models.FloatField(default=5.0, help_text='Seconds to wait when trying to connect to the comment service.'), ), ] diff --git a/openedx/core/djangoapps/django_comment_common/migrations/0005_coursediscussionsettings.py b/openedx/core/djangoapps/django_comment_common/migrations/0005_coursediscussionsettings.py index 965db95fe15..4d8efb14c41 100644 --- a/openedx/core/djangoapps/django_comment_common/migrations/0005_coursediscussionsettings.py +++ b/openedx/core/djangoapps/django_comment_common/migrations/0005_coursediscussionsettings.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - from django.db import migrations, models from opaque_keys.edx.django.models import CourseKeyField diff --git a/openedx/core/djangoapps/django_comment_common/migrations/0006_coursediscussionsettings_discussions_id_map.py b/openedx/core/djangoapps/django_comment_common/migrations/0006_coursediscussionsettings_discussions_id_map.py index b3e91a2d94a..bc30ad314f1 100644 --- a/openedx/core/djangoapps/django_comment_common/migrations/0006_coursediscussionsettings_discussions_id_map.py +++ b/openedx/core/djangoapps/django_comment_common/migrations/0006_coursediscussionsettings_discussions_id_map.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.12 on 2018-04-23 21:09 @@ -16,6 +15,6 @@ class Migration(migrations.Migration): migrations.AddField( model_name='coursediscussionsettings', name='discussions_id_map', - field=jsonfield.fields.JSONField(blank=True, help_text=u'Key/value store mapping discussion IDs to discussion XBlock usage keys.', null=True), + field=jsonfield.fields.JSONField(blank=True, help_text='Key/value store mapping discussion IDs to discussion XBlock usage keys.', null=True), ), ] diff --git a/openedx/core/djangoapps/django_comment_common/migrations/0007_discussionsidmapping.py b/openedx/core/djangoapps/django_comment_common/migrations/0007_discussionsidmapping.py index 38f281c2155..ba396e025c1 100644 --- a/openedx/core/djangoapps/django_comment_common/migrations/0007_discussionsidmapping.py +++ b/openedx/core/djangoapps/django_comment_common/migrations/0007_discussionsidmapping.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-06-13 12:10 @@ -18,7 +17,7 @@ class Migration(migrations.Migration): name='DiscussionsIdMapping', fields=[ ('course_id', opaque_keys.edx.django.models.CourseKeyField(db_index=True, max_length=255, primary_key=True, serialize=False)), - ('mapping', jsonfield.fields.JSONField(help_text=u'Key/value store mapping discussion IDs to discussion XBlock usage keys.')), + ('mapping', jsonfield.fields.JSONField(help_text='Key/value store mapping discussion IDs to discussion XBlock usage keys.')), ], options={ 'db_table': 'django_comment_common_discussionsidmapping', diff --git a/openedx/core/djangoapps/django_comment_common/migrations/0008_role_user_index.py b/openedx/core/djangoapps/django_comment_common/migrations/0008_role_user_index.py index d1a766acc6c..8acc552d8cc 100644 --- a/openedx/core/djangoapps/django_comment_common/migrations/0008_role_user_index.py +++ b/openedx/core/djangoapps/django_comment_common/migrations/0008_role_user_index.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- - - from django.db import migrations diff --git a/openedx/core/djangoapps/django_comment_common/models.py b/openedx/core/djangoapps/django_comment_common/models.py index 5bc99a2320d..47795da9fe6 100644 --- a/openedx/core/djangoapps/django_comment_common/models.py +++ b/openedx/core/djangoapps/django_comment_common/models.py @@ -14,7 +14,6 @@ from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_noop from jsonfield.fields import JSONField from opaque_keys.edx.django.models import CourseKeyField -from six import text_type from openedx.core.djangoapps.xmodule_django.models import NoneToEmptyManager from common.djangoapps.student.models import CourseEnrollment @@ -64,7 +63,7 @@ def assign_role(course_id, user, rolename): """ role, created = Role.objects.get_or_create(course_id=course_id, name=rolename) if created: - logging.info(u"EDUCATOR-1635: Created role {} for course {}".format(role, course_id)) + logging.info(f"EDUCATOR-1635: Created role {role} for course {course_id}") user.roles.add(role) @@ -82,12 +81,12 @@ class Role(models.Model): users = models.ManyToManyField(User, related_name="roles") course_id = CourseKeyField(max_length=255, blank=True, db_index=True) - class Meta(object): + class Meta: # use existing table that was originally created from lms.djangoapps.discussion.django_comment_client app db_table = 'django_comment_client_role' def __str__(self): - return self.name + " for " + (text_type(self.course_id) if self.course_id else "all courses") + return self.name + " for " + (str(self.course_id) if self.course_id else "all courses") # TODO the name of this method is a little bit confusing, # since it's one-off and doesn't handle inheritance later @@ -98,7 +97,7 @@ class Role(models.Model): """ if role.course_id and role.course_id != self.course_id: logging.warning( - u"%s cannot inherit permissions from %s due to course_id inconsistency", + "%s cannot inherit permissions from %s due to course_id inconsistency", self, role, ) @@ -138,7 +137,7 @@ class Permission(models.Model): name = models.CharField(max_length=30, null=False, blank=False, primary_key=True) roles = models.ManyToManyField(Role, related_name="permissions") - class Meta(object): + class Meta: # use existing table that was originally created from lms.djangoapps.discussion.django_comment_client app db_table = 'django_comment_client_permission' @@ -205,7 +204,7 @@ class ForumsConfig(ConfigurationModel): connection_timeout = models.FloatField( default=5.0, - help_text=u"Seconds to wait when trying to connect to the comment service.", + help_text="Seconds to wait when trying to connect to the comment service.", ) class Meta(ConfigurationModel.Meta): @@ -221,7 +220,7 @@ class ForumsConfig(ConfigurationModel): """ Simple representation so the admin screen looks less ugly. """ - return u"ForumsConfig: timeout={}".format(self.connection_timeout) + return f"ForumsConfig: timeout={self.connection_timeout}" class CourseDiscussionSettings(models.Model): @@ -239,7 +238,7 @@ class CourseDiscussionSettings(models.Model): discussions_id_map = JSONField( null=True, blank=True, - help_text=u"Key/value store mapping discussion IDs to discussion XBlock usage keys.", + help_text="Key/value store mapping discussion IDs to discussion XBlock usage keys.", ) always_divide_inline_discussions = models.BooleanField(default=False) _divided_discussions = models.TextField(db_column='divided_discussions', null=True, blank=True) # JSON list @@ -250,7 +249,7 @@ class CourseDiscussionSettings(models.Model): ASSIGNMENT_TYPE_CHOICES = ((NONE, 'None'), (COHORT, 'Cohort'), (ENROLLMENT_TRACK, 'Enrollment Track')) division_scheme = models.CharField(max_length=20, choices=ASSIGNMENT_TYPE_CHOICES, default=NONE) - class Meta(object): + class Meta: # use existing table that was originally created from django_comment_common app db_table = 'django_comment_common_coursediscussionsettings' @@ -277,10 +276,10 @@ class DiscussionsIdMapping(models.Model): """ course_id = CourseKeyField(db_index=True, primary_key=True, max_length=255) mapping = JSONField( - help_text=u"Key/value store mapping discussion IDs to discussion XBlock usage keys.", + help_text="Key/value store mapping discussion IDs to discussion XBlock usage keys.", ) - class Meta(object): + class Meta: # use existing table that was originally created from django_comment_common app db_table = 'django_comment_common_discussionsidmapping' diff --git a/openedx/core/djangoapps/django_comment_common/tests.py b/openedx/core/djangoapps/django_comment_common/tests.py index 4284202068c..5d996d90ce9 100644 --- a/openedx/core/djangoapps/django_comment_common/tests.py +++ b/openedx/core/djangoapps/django_comment_common/tests.py @@ -1,12 +1,10 @@ # pylint: disable=missing-docstring -import six import pytest from contracts import new_contract from django.test import TestCase from opaque_keys.edx.locator import CourseLocator -from six import text_type from openedx.core.djangoapps.course_groups.cohorts import CourseCohortsSettings from openedx.core.djangoapps.django_comment_common.models import CourseDiscussionSettings, Role @@ -20,7 +18,7 @@ from xmodule.modulestore.django import modulestore from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase from xmodule.modulestore.tests.factories import CourseFactory -new_contract('basestring', six.string_types[0]) +new_contract('basestring', str) class RoleAssignmentTest(TestCase): @@ -30,7 +28,7 @@ class RoleAssignmentTest(TestCase): """ def setUp(self): - super(RoleAssignmentTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() # Check a staff account because those used to get the Moderator role self.staff_user = User.objects.create_user( "patty", @@ -78,7 +76,7 @@ class RoleAssignmentTest(TestCase): class CourseDiscussionSettingsTest(ModuleStoreTestCase): def setUp(self): - super(CourseDiscussionSettingsTest, self).setUp() # lint-amnesty, pylint: disable=super-with-arguments + super().setUp() self.course = CourseFactory.create() def test_get_course_discussion_settings(self): @@ -128,7 +126,7 @@ class CourseDiscussionSettingsTest(ModuleStoreTestCase): def test_invalid_data_types(self): exception_msg_template = "Incorrect field type for `{}`. Type must be `{}`" fields = [ - {'name': 'division_scheme', 'type': six.string_types[0]}, + {'name': 'division_scheme', 'type': (str,)[0]}, {'name': 'always_divide_inline_discussions', 'type': bool}, {'name': 'divided_discussions', 'type': list} ] @@ -138,4 +136,4 @@ class CourseDiscussionSettingsTest(ModuleStoreTestCase): with pytest.raises(ValueError) as value_error: set_course_discussion_settings(self.course.id, **{field['name']: invalid_value}) - assert text_type(value_error.value) == exception_msg_template.format(field['name'], field['type'].__name__) + assert str(value_error.value) == exception_msg_template.format(field['name'], field['type'].__name__) diff --git a/openedx/core/djangoapps/django_comment_common/utils.py b/openedx/core/djangoapps/django_comment_common/utils.py index e94257d8def..004479341dc 100644 --- a/openedx/core/djangoapps/django_comment_common/utils.py +++ b/openedx/core/djangoapps/django_comment_common/utils.py @@ -4,7 +4,6 @@ Common comment client utility functions. """ -import six from contracts import new_contract from openedx.core.djangoapps.course_groups.cohorts import get_legacy_discussion_settings @@ -19,10 +18,10 @@ from openedx.core.djangoapps.django_comment_common.models import ( ) from openedx.core.lib.cache_utils import request_cached -new_contract('basestring', six.string_types[0]) +new_contract('basestring', str) -class ThreadContext(object): +class ThreadContext: """ An enumeration that represents the context of a thread. Used primarily by the comments service. """ STANDALONE = 'standalone' COURSE = 'course' @@ -152,7 +151,7 @@ def set_course_discussion_settings(course_key, **kwargs): A CourseDiscussionSettings object. """ fields = { - 'division_scheme': six.string_types[0], + 'division_scheme': (str,)[0], 'always_divide_inline_discussions': bool, 'divided_discussions': list, } @@ -161,7 +160,7 @@ def set_course_discussion_settings(course_key, **kwargs): for field, field_type in fields.items(): if field in kwargs: if not isinstance(kwargs[field], field_type): - raise ValueError(u"Incorrect field type for `{}`. Type must be `{}`".format(field, field_type.__name__)) + raise ValueError(f"Incorrect field type for `{field}`. Type must be `{field_type.__name__}`") setattr(course_discussion_settings, field, kwargs[field]) course_discussion_settings.save() -- GitLab