diff --git a/common/djangoapps/student/middleware.py b/common/djangoapps/student/middleware.py index ca2a4eedf5..940c249662 100644 --- a/common/djangoapps/student/middleware.py +++ b/common/djangoapps/student/middleware.py @@ -6,13 +6,14 @@ disabled accounts from accessing the site. from django.conf import settings from django.http import HttpResponseForbidden +from django.utils.deprecation import MiddlewareMixin from django.utils.translation import ugettext as _ from openedx.core.djangolib.markup import HTML, Text from student.models import UserStanding -class UserStandingMiddleware(object): +class UserStandingMiddleware(MiddlewareMixin): """ Checks a user's standing on request. Returns a 403 if the user's status is 'disabled'. diff --git a/common/djangoapps/third_party_auth/middleware.py b/common/djangoapps/third_party_auth/middleware.py index 7205340758..836eab3a06 100644 --- a/common/djangoapps/third_party_auth/middleware.py +++ b/common/djangoapps/third_party_auth/middleware.py @@ -5,6 +5,7 @@ import six.moves.urllib.parse # pylint: disable=import-error from django.contrib import messages from django.shortcuts import redirect from django.urls import reverse +from django.utils.deprecation import MiddlewareMixin from django.utils.translation import ugettext as _ from requests import HTTPError from social_django.middleware import SocialAuthExceptionMiddleware @@ -14,7 +15,7 @@ from student.helpers import get_next_url_for_login_page from . import pipeline -class ExceptionMiddleware(SocialAuthExceptionMiddleware): +class ExceptionMiddleware(SocialAuthExceptionMiddleware, MiddlewareMixin): """Custom middleware that handles conditional redirection.""" def get_redirect_uri(self, request, exception): diff --git a/common/djangoapps/track/middleware.py b/common/djangoapps/track/middleware.py index 61e0efdfd9..6e8abb96cb 100644 --- a/common/djangoapps/track/middleware.py +++ b/common/djangoapps/track/middleware.py @@ -15,6 +15,7 @@ import sys import six from django.conf import settings +from django.utils.deprecation import MiddlewareMixin from eventtracking import tracker from ipware.ip import get_ip @@ -34,7 +35,7 @@ META_KEY_TO_CONTEXT_KEY = { } -class TrackMiddleware(object): +class TrackMiddleware(MiddlewareMixin): """ Tracks all requests made, as well as setting up context for other server emitted events. diff --git a/lms/djangoapps/course_wiki/middleware.py b/lms/djangoapps/course_wiki/middleware.py index 293049a935..5463e6f4f1 100644 --- a/lms/djangoapps/course_wiki/middleware.py +++ b/lms/djangoapps/course_wiki/middleware.py @@ -5,6 +5,7 @@ from django.conf import settings from django.core.exceptions import PermissionDenied from django.http import Http404 from django.shortcuts import redirect +from django.utils.deprecation import MiddlewareMixin from six import text_type from six.moves.urllib.parse import urlparse # pylint: disable=import-error from wiki.models import reverse @@ -16,7 +17,7 @@ from openedx.features.enterprise_support.api import get_enterprise_consent_url from student.models import CourseEnrollment -class WikiAccessMiddleware(object): +class WikiAccessMiddleware(MiddlewareMixin): """ This middleware wraps calls to django-wiki in order to handle authentication and redirection between the root wiki and the course wikis. diff --git a/lms/djangoapps/courseware/middleware.py b/lms/djangoapps/courseware/middleware.py index d5a40b957c..3ec3fa525a 100644 --- a/lms/djangoapps/courseware/middleware.py +++ b/lms/djangoapps/courseware/middleware.py @@ -4,12 +4,13 @@ Middleware for the courseware app from django.shortcuts import redirect +from django.utils.deprecation import MiddlewareMixin from lms.djangoapps.courseware.exceptions import Redirect from openedx.core.lib.request_utils import COURSE_REGEX -class RedirectMiddleware(object): +class RedirectMiddleware(MiddlewareMixin): """ Catch Redirect exceptions and redirect the user to the expected URL. """ @@ -21,7 +22,7 @@ class RedirectMiddleware(object): return redirect(exception.url) -class CacheCourseIdMiddleware(object): +class CacheCourseIdMiddleware(MiddlewareMixin): """Middleware that adds course_id to user request session.""" def process_request(self, request): diff --git a/lms/djangoapps/discussion/django_comment_client/middleware.py b/lms/djangoapps/discussion/django_comment_client/middleware.py index 5d98540668..fd76a9060e 100644 --- a/lms/djangoapps/discussion/django_comment_client/middleware.py +++ b/lms/djangoapps/discussion/django_comment_client/middleware.py @@ -4,6 +4,7 @@ import json import logging +from django.utils.deprecation import MiddlewareMixin from six import text_type from lms.djangoapps.discussion.django_comment_client.utils import JsonError @@ -12,7 +13,7 @@ from openedx.core.djangoapps.django_comment_common.comment_client import Comment log = logging.getLogger(__name__) -class AjaxExceptionMiddleware(object): +class AjaxExceptionMiddleware(MiddlewareMixin): """ Middleware that captures CommentClientRequestErrors during ajax requests and tranforms them into json responses diff --git a/lms/djangoapps/discussion/django_comment_client/utils.py b/lms/djangoapps/discussion/django_comment_client/utils.py index 7708474dc2..6675516fce 100644 --- a/lms/djangoapps/discussion/django_comment_client/utils.py +++ b/lms/djangoapps/discussion/django_comment_client/utils.py @@ -12,6 +12,7 @@ from django.contrib.auth.models import User from django.db import connection from django.http import HttpResponse from django.urls import reverse +from django.utils.deprecation import MiddlewareMixin from opaque_keys.edx.keys import CourseKey, UsageKey from opaque_keys.edx.locations import i4xEncoder from pytz import UTC @@ -526,7 +527,7 @@ class HtmlResponse(HttpResponse): super(HtmlResponse, self).__init__(html, content_type='text/plain') -class ViewNameMiddleware(object): +class ViewNameMiddleware(MiddlewareMixin): """ Django middleware object to inject view name into request context """ @@ -537,7 +538,7 @@ class ViewNameMiddleware(object): request.view_name = view_func.__name__ -class QueryCountDebugMiddleware(object): +class QueryCountDebugMiddleware(MiddlewareMixin): """ This middleware will log the number of queries run and the total time taken for each request (with a diff --git a/lms/djangoapps/mobile_api/middleware.py b/lms/djangoapps/mobile_api/middleware.py index 0258f7f431..7fc73658fb 100644 --- a/lms/djangoapps/mobile_api/middleware.py +++ b/lms/djangoapps/mobile_api/middleware.py @@ -8,6 +8,7 @@ from datetime import datetime from django.conf import settings from django.core.cache import cache from django.http import HttpResponse +from django.utils.deprecation import MiddlewareMixin from pytz import UTC import six @@ -18,7 +19,7 @@ from openedx.core.lib.cache_utils import get_cache from openedx.core.lib.mobile_utils import is_request_from_mobile_app -class AppVersionUpgrade(object): +class AppVersionUpgrade(MiddlewareMixin): """ Middleware class to keep track of mobile application version being used. """ diff --git a/openedx/core/djangoapps/cache_toolbox/middleware.py b/openedx/core/djangoapps/cache_toolbox/middleware.py index 9925fd8035..13b113f434 100644 --- a/openedx/core/djangoapps/cache_toolbox/middleware.py +++ b/openedx/core/djangoapps/cache_toolbox/middleware.py @@ -86,6 +86,7 @@ from django.contrib.auth import HASH_SESSION_KEY from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.auth.models import AnonymousUser, User from django.utils.crypto import constant_time_compare +from django.utils.deprecation import MiddlewareMixin from openedx.core.djangoapps.safe_sessions.middleware import SafeSessionMiddleware @@ -94,12 +95,13 @@ from .model import cache_model log = getLogger(__name__) -class CacheBackedAuthenticationMiddleware(AuthenticationMiddleware): +class CacheBackedAuthenticationMiddleware(AuthenticationMiddleware, MiddlewareMixin): """ See documentation above. """ - def __init__(self): + def __init__(self, *args, **kwargs): cache_model(User) + super(CacheBackedAuthenticationMiddleware, self).__init__(*args, **kwargs) def process_request(self, request): try: diff --git a/openedx/core/djangoapps/contentserver/middleware.py b/openedx/core/djangoapps/contentserver/middleware.py index 39b0dfac09..ff810fff5b 100644 --- a/openedx/core/djangoapps/contentserver/middleware.py +++ b/openedx/core/djangoapps/contentserver/middleware.py @@ -3,31 +3,40 @@ Middleware to serve assets. """ -import logging import datetime +import logging + import six +from django.http import ( + HttpResponse, + HttpResponseBadRequest, + HttpResponseForbidden, + HttpResponseNotFound, + HttpResponseNotModified, + HttpResponsePermanentRedirect +) +from django.utils.deprecation import MiddlewareMixin +from opaque_keys import InvalidKeyError +from opaque_keys.edx.locator import AssetLocator +from six import text_type + +from openedx.core.djangoapps.header_control import force_header_for_response +from student.models import CourseEnrollment +from xmodule.assetstore.assetmgr import AssetManager +from xmodule.contentstore.content import XASSET_LOCATION_TAG, StaticContent +from xmodule.exceptions import NotFoundError +from xmodule.modulestore import InvalidLocationError +from xmodule.modulestore.exceptions import ItemNotFoundError + +from .caching import get_cached_content, set_cached_content +from .models import CdnUserAgentsConfig, CourseAssetCacheTtlConfig + log = logging.getLogger(__name__) try: import newrelic.agent except ImportError: newrelic = None # pylint: disable=invalid-name -from django.http import ( - HttpResponse, HttpResponseNotModified, HttpResponseForbidden, - HttpResponseBadRequest, HttpResponseNotFound, HttpResponsePermanentRedirect) -from six import text_type -from student.models import CourseEnrollment -from xmodule.assetstore.assetmgr import AssetManager -from xmodule.contentstore.content import StaticContent, XASSET_LOCATION_TAG -from xmodule.modulestore import InvalidLocationError -from opaque_keys import InvalidKeyError -from opaque_keys.edx.locator import AssetLocator -from openedx.core.djangoapps.header_control import force_header_for_response -from .caching import get_cached_content, set_cached_content -from xmodule.modulestore.exceptions import ItemNotFoundError -from xmodule.exceptions import NotFoundError - -from .models import CourseAssetCacheTtlConfig, CdnUserAgentsConfig # TODO: Soon as we have a reasonable way to serialize/deserialize AssetKeys, we need # to change this file so instead of using course_id_partial, we're just using asset keys @@ -35,7 +44,7 @@ from .models import CourseAssetCacheTtlConfig, CdnUserAgentsConfig HTTP_DATE_FORMAT = u"%a, %d %b %Y %H:%M:%S GMT" -class StaticContentServer(object): +class StaticContentServer(MiddlewareMixin): """ Serves course assets to end users. Colloquially referred to as "contentserver." """ diff --git a/openedx/core/djangoapps/cors_csrf/middleware.py b/openedx/core/djangoapps/cors_csrf/middleware.py index 7a911b7317..0367b5f269 100644 --- a/openedx/core/djangoapps/cors_csrf/middleware.py +++ b/openedx/core/djangoapps/cors_csrf/middleware.py @@ -48,6 +48,7 @@ import logging from django.conf import settings from django.core.exceptions import ImproperlyConfigured, MiddlewareNotUsed from django.middleware.csrf import CsrfViewMiddleware +from django.utils.deprecation import MiddlewareMixin from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_check @@ -55,14 +56,16 @@ from .helpers import is_cross_domain_request_allowed, skip_cross_domain_referer_ log = logging.getLogger(__name__) -class CorsCSRFMiddleware(CsrfViewMiddleware): +class CorsCSRFMiddleware(CsrfViewMiddleware, MiddlewareMixin): """ Middleware for handling CSRF checks with CORS requests """ - def __init__(self): + + def __init__(self, *args, **kwargs): """Disable the middleware if the feature flag is disabled. """ if not settings.FEATURES.get('ENABLE_CORS_HEADERS'): raise MiddlewareNotUsed() + super(CorsCSRFMiddleware, self).__init__(*args, **kwargs) def process_view(self, request, callback, callback_args, callback_kwargs): """Skip the usual CSRF referer check if this is an allowed cross-domain request. """ @@ -74,7 +77,7 @@ class CorsCSRFMiddleware(CsrfViewMiddleware): return super(CorsCSRFMiddleware, self).process_view(request, callback, callback_args, callback_kwargs) -class CsrfCrossDomainCookieMiddleware(object): +class CsrfCrossDomainCookieMiddleware(MiddlewareMixin): """Set an additional "cross-domain" CSRF cookie. Usage: @@ -91,7 +94,7 @@ class CsrfCrossDomainCookieMiddleware(object): """ - def __init__(self): + def __init__(self, *args, **kwargs): """Disable the middleware if the feature is not enabled. """ if not settings.FEATURES.get('ENABLE_CROSS_DOMAIN_CSRF_COOKIE'): raise MiddlewareNotUsed() @@ -107,6 +110,7 @@ class CsrfCrossDomainCookieMiddleware(object): "You must set `CROSS_DOMAIN_CSRF_COOKIE_DOMAIN` when " "`FEATURES['ENABLE_CROSS_DOMAIN_CSRF_COOKIE']` is True." ) + super(CsrfCrossDomainCookieMiddleware, self).__init__(*args, **kwargs) def process_response(self, request, response): """Set the cross-domain CSRF cookie. """ diff --git a/openedx/core/djangoapps/dark_lang/middleware.py b/openedx/core/djangoapps/dark_lang/middleware.py index ee43b06ee6..72ecb7f156 100644 --- a/openedx/core/djangoapps/dark_lang/middleware.py +++ b/openedx/core/djangoapps/dark_lang/middleware.py @@ -12,6 +12,7 @@ the SessionMiddleware. from django.conf import settings from django.utils.translation import LANGUAGE_SESSION_KEY from django.utils.translation.trans_real import parse_accept_lang_header +from django.utils.deprecation import MiddlewareMixin from openedx.core.djangoapps.dark_lang import DARK_LANGUAGE_KEY from openedx.core.djangoapps.dark_lang.models import DarkLangConfig @@ -54,7 +55,7 @@ def _dark_parse_accept_lang_header(accept): return django_langs -class DarkLangMiddleware(object): +class DarkLangMiddleware(MiddlewareMixin): """ Middleware for dark-launching languages. diff --git a/openedx/core/djangoapps/embargo/middleware.py b/openedx/core/djangoapps/embargo/middleware.py index 4d355a9d85..4e499c8230 100644 --- a/openedx/core/djangoapps/embargo/middleware.py +++ b/openedx/core/djangoapps/embargo/middleware.py @@ -32,6 +32,7 @@ import re from django.conf import settings from django.core.exceptions import MiddlewareNotUsed from django.urls import reverse +from django.utils.deprecation import MiddlewareMixin from django.shortcuts import redirect from ipware.ip import get_ip @@ -43,7 +44,7 @@ from .models import IPFilter log = logging.getLogger(__name__) -class EmbargoMiddleware(object): +class EmbargoMiddleware(MiddlewareMixin): """Middleware for embargoing site and courses. """ ALLOW_URL_PATTERNS = [ @@ -57,10 +58,11 @@ class EmbargoMiddleware(object): re.compile(r'^/admin/'), ] - def __init__(self): + def __init__(self, *args, **kwargs): # If embargoing is turned off, make this middleware do nothing if not settings.FEATURES.get('EMBARGO'): raise MiddlewareNotUsed() + super(EmbargoMiddleware, self).__init__(*args, **kwargs) def process_request(self, request): """Block requests based on embargo rules. diff --git a/openedx/core/djangoapps/geoinfo/middleware.py b/openedx/core/djangoapps/geoinfo/middleware.py index b0b128a6da..6f0399d9ed 100644 --- a/openedx/core/djangoapps/geoinfo/middleware.py +++ b/openedx/core/djangoapps/geoinfo/middleware.py @@ -15,12 +15,13 @@ import logging import geoip2.database from django.conf import settings +from django.utils.deprecation import MiddlewareMixin from ipware.ip import get_real_ip log = logging.getLogger(__name__) -class CountryMiddleware(object): +class CountryMiddleware(MiddlewareMixin): """ Identify the country by IP address. """ diff --git a/openedx/core/djangoapps/header_control/middleware.py b/openedx/core/djangoapps/header_control/middleware.py index e00e879149..b2f003bcd2 100644 --- a/openedx/core/djangoapps/header_control/middleware.py +++ b/openedx/core/djangoapps/header_control/middleware.py @@ -2,11 +2,11 @@ Middleware used for adjusting headers in a response before it is sent to the end user. """ - +from django.utils.deprecation import MiddlewareMixin import six -class HeaderControlMiddleware(object): +class HeaderControlMiddleware(MiddlewareMixin): """ Middleware that can modify/remove headers in a response. diff --git a/openedx/core/djangoapps/lang_pref/middleware.py b/openedx/core/djangoapps/lang_pref/middleware.py index d63fc2035f..c3c5fc1b17 100644 --- a/openedx/core/djangoapps/lang_pref/middleware.py +++ b/openedx/core/djangoapps/lang_pref/middleware.py @@ -4,6 +4,7 @@ Middleware for Language Preferences from django.conf import settings +from django.utils.deprecation import MiddlewareMixin from django.utils.translation import LANGUAGE_SESSION_KEY from django.utils.translation.trans_real import parse_accept_lang_header @@ -13,7 +14,7 @@ from openedx.core.djangoapps.user_api.preferences.api import get_user_preference from openedx.core.lib.mobile_utils import is_request_from_mobile_app -class LanguagePreferenceMiddleware(object): +class LanguagePreferenceMiddleware(MiddlewareMixin): """ Middleware for user preferences. diff --git a/openedx/core/djangoapps/safe_sessions/middleware.py b/openedx/core/djangoapps/safe_sessions/middleware.py index 65a4b0be45..5f7f25202a 100644 --- a/openedx/core/djangoapps/safe_sessions/middleware.py +++ b/openedx/core/djangoapps/safe_sessions/middleware.py @@ -70,6 +70,7 @@ from django.contrib.sessions.middleware import SessionMiddleware from django.core import signing from django.http import HttpResponse from django.utils.crypto import get_random_string +from django.utils.deprecation import MiddlewareMixin from django.utils.encoding import python_2_unicode_compatible from six import text_type # pylint: disable=ungrouped-imports @@ -238,7 +239,7 @@ class SafeCookieData(object): ) -class SafeSessionMiddleware(SessionMiddleware): +class SafeSessionMiddleware(SessionMiddleware, MiddlewareMixin): """ A safer middleware implementation that uses SafeCookieData instead of just the session id to lookup and verify a user's session. diff --git a/openedx/core/djangoapps/session_inactivity_timeout/middleware.py b/openedx/core/djangoapps/session_inactivity_timeout/middleware.py index fdebb66eea..eb5633ff12 100644 --- a/openedx/core/djangoapps/session_inactivity_timeout/middleware.py +++ b/openedx/core/djangoapps/session_inactivity_timeout/middleware.py @@ -14,11 +14,12 @@ from datetime import datetime, timedelta from django.conf import settings from django.contrib import auth +from django.utils.deprecation import MiddlewareMixin LAST_TOUCH_KEYNAME = 'SessionInactivityTimeout:last_touch' -class SessionInactivityTimeout(object): +class SessionInactivityTimeout(MiddlewareMixin): """ Middleware class to keep track of activity on a given session """ diff --git a/openedx/core/djangoapps/site_configuration/middleware.py b/openedx/core/djangoapps/site_configuration/middleware.py index 2a2ccd7e01..227cc51548 100644 --- a/openedx/core/djangoapps/site_configuration/middleware.py +++ b/openedx/core/djangoapps/site_configuration/middleware.py @@ -4,11 +4,12 @@ This file contains Django middleware related to the site_configuration app. from django.conf import settings +from django.utils.deprecation import MiddlewareMixin from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers -class SessionCookieDomainOverrideMiddleware(object): +class SessionCookieDomainOverrideMiddleware(MiddlewareMixin): """ Special case middleware which should be at the very end of the MIDDLEWARE list (so that it runs first on the process_response chain). This middleware will define a wrapper function for the set_cookie() function diff --git a/openedx/core/djangoapps/theming/middleware.py b/openedx/core/djangoapps/theming/middleware.py index b74cdb4b33..8a5a2e3df7 100644 --- a/openedx/core/djangoapps/theming/middleware.py +++ b/openedx/core/djangoapps/theming/middleware.py @@ -8,12 +8,13 @@ Note: from django.conf import settings +from django.utils.deprecation import MiddlewareMixin from .models import SiteTheme from .views import get_user_preview_site_theme -class CurrentSiteThemeMiddleware(object): +class CurrentSiteThemeMiddleware(MiddlewareMixin): """ Middleware that sets `site_theme` attribute to request object. """ diff --git a/openedx/core/djangoapps/user_api/middleware.py b/openedx/core/djangoapps/user_api/middleware.py index e3faf468d3..927ee7dc7d 100644 --- a/openedx/core/djangoapps/user_api/middleware.py +++ b/openedx/core/djangoapps/user_api/middleware.py @@ -3,6 +3,7 @@ Middleware for user api. Adds user's tags to tracking event context. """ +from django.utils.deprecation import MiddlewareMixin from eventtracking import tracker from opaque_keys import InvalidKeyError @@ -13,7 +14,7 @@ from track.contexts import COURSE_REGEX from .models import UserCourseTag -class UserTagsEventContextMiddleware(object): +class UserTagsEventContextMiddleware(MiddlewareMixin): """Middleware that adds a user's tags to tracking event context.""" CONTEXT_NAME = 'user_tags_context' diff --git a/openedx/core/lib/x_forwarded_for/middleware.py b/openedx/core/lib/x_forwarded_for/middleware.py index 2a1fa3b3e0..e10f89cdf1 100644 --- a/openedx/core/lib/x_forwarded_for/middleware.py +++ b/openedx/core/lib/x_forwarded_for/middleware.py @@ -3,9 +3,10 @@ Middleware to use the X-Forwarded-For header as the request IP. Updated the libray to use HTTP_HOST and X-Forwarded-Port as SERVER_NAME and SERVER_PORT. """ +from django.utils.deprecation import MiddlewareMixin -class XForwardedForMiddleware(object): +class XForwardedForMiddleware(MiddlewareMixin): """ Gunicorn 19.0 has breaking changes for REMOTE_ADDR, SERVER_* headers that can not override with forwarded and host headers.