Old style mixin compatibility with django2.2
This commit is contained in:
Aarif
2020-01-09 20:15:17 +05:00
committed by Awais Qureshi
parent 0cb0867cd7
commit 97d327feeb
22 changed files with 81 additions and 47 deletions

View File

@@ -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:

View File

@@ -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."
"""

View File

@@ -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. """

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.
"""

View File

@@ -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.

View File

@@ -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.

View File

@@ -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.

View File

@@ -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
"""

View File

@@ -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

View File

@@ -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.
"""

View File

@@ -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'

View File

@@ -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.