MiddlewareMixin is a class within the django.utils.deprecation module of the Django project.
Auditlog (project documentation) is a Django app that logs changes to Python objects, similar to the Django admin's logs but with more details and output formats. Auditlog's source code is provided as open source under the MIT license.
AuditLog / src / auditlog / middleware.py
# middleware.py
from __future__ import unicode_literals
import threading
import time
from django.conf import settings
from django.db.models.signals import pre_save
from django.utils.functional import curry
from django.apps import apps
from auditlog.models import LogEntry
from auditlog.compat import is_authenticated
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
threadlocal = threading.local()
class AuditlogMiddleware(MiddlewareMixin):
def process_request(self, request):
threadlocal.auditlog = {
'signal_duid': (self.__class__, time.time()),
'remote_addr': request.META.get('REMOTE_ADDR'),
}
if request.META.get('HTTP_X_FORWARDED_FOR'):
threadlocal.auditlog['remote_addr'] = request.META.get('HTTP_X_FORWARDED_FOR').split(',')[0]
if hasattr(request, 'user') and is_authenticated(request.user):
set_actor = curry(self.set_actor, user=request.user, signal_duid=threadlocal.auditlog['signal_duid'])
pre_save.connect(set_actor, sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'], weak=False)
def process_response(self, request, response):
if hasattr(threadlocal, 'auditlog'):
pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'])
return response
def process_exception(self, request, exception):
if hasattr(threadlocal, 'auditlog'):
pre_save.disconnect(sender=LogEntry, dispatch_uid=threadlocal.auditlog['signal_duid'])
## ... source file continues with no further MiddlewareMixin examples...
django-angular (project examples website) is a library with helper code to make it easier to use Angular as the front-end to Django projects. The code for django-angular is open source under the MIT license.
django-angular / djng / middleware.py
# middleware.py
from django import http
from django.urls import reverse
from django.utils.http import unquote
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
MiddlewareMixin = object
class AngularUrlMiddleware(MiddlewareMixin):
ANGULAR_REVERSE = '/angular/reverse/'
def process_request(self, request):
if request.path == self.ANGULAR_REVERSE:
url_name = request.GET.get('djng_url_name')
url_args = request.GET.getlist('djng_url_args', [])
url_kwargs = {}
url_args = filter(lambda x: x, url_args)
for param in request.GET:
if param.startswith('djng_url_kwarg_'):
if request.GET[param]:
url_kwargs[param[15:]] = request.GET[param] # [15:] to remove 'djng_url_kwarg' prefix
url = unquote(reverse(url_name, args=url_args, kwargs=url_kwargs))
assert not url.startswith(self.ANGULAR_REVERSE), "Prevent recursive requests"
request.path = request.path_info = url
request.environ['PATH_INFO'] = url
query = request.GET.copy()
for key in request.GET:
if key.startswith('djng_url'):
query.pop(key, None)
## ... source file continues with no further MiddlewareMixin examples...
django-cors-headers is an open source library for enabling Cross-Origin Resource Sharing (CORS) handling in your Django web applications and appropriately dealing with HTTP headers for CORS requests.
django-cors-headers / src/corsheaders / middleware.py
# middleware.py
import re
from urllib.parse import urlparse
from django import http
from django.utils.cache import patch_vary_headers
from django.utils.deprecation import MiddlewareMixin
from corsheaders.conf import conf
from corsheaders.signals import check_request_enabled
ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"
ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"
ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"
ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"
ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"
ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age"
class CorsPostCsrfMiddleware(MiddlewareMixin):
def _https_referer_replace_reverse(self, request):
if conf.CORS_REPLACE_HTTPS_REFERER and "ORIGINAL_HTTP_REFERER" in request.META:
http_referer = request.META["ORIGINAL_HTTP_REFERER"]
request.META["HTTP_REFERER"] = http_referer
del request.META["ORIGINAL_HTTP_REFERER"]
def process_request(self, request):
self._https_referer_replace_reverse(request)
return None
def process_view(self, request, callback, callback_args, callback_kwargs):
self._https_referer_replace_reverse(request)
return None
class CorsMiddleware(MiddlewareMixin):
def _https_referer_replace(self, request):
origin = request.META.get("HTTP_ORIGIN")
if (
request.is_secure()
and origin
and "ORIGINAL_HTTP_REFERER" not in request.META
):
url = urlparse(origin)
if not conf.CORS_ORIGIN_ALLOW_ALL and not self.origin_found_in_white_lists(
origin, url
):
return
try:
http_referer = request.META["HTTP_REFERER"]
http_host = "https://%s/" % request.META["HTTP_HOST"]
request.META = request.META.copy()
request.META["ORIGINAL_HTTP_REFERER"] = http_referer
request.META["HTTP_REFERER"] = http_host
except KeyError:
pass
## ... source file continues with no further MiddlewareMixin examples...
django-downloadview (project documentation and PyPI package information) is a Django extension for serving downloads through your web application. While typically you would use a web server to handle static content, sometimes you need to control file access, such as requiring a user to register before downloading a PDF. In that situations, django-downloadview is a handy library to avoid boilerplate code for common scenarios.
django-downloadview / django_downloadview / middlewares.py
# middlewares.py
import collections
import copy
import os
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django_downloadview.response import DownloadResponse
from django_downloadview.utils import import_member
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError:
class MiddlewareMixin(object):
def __init__(self, get_response=None):
super(MiddlewareMixin, self).__init__()
AUTO_CONFIGURE = object()
def is_download_response(response):
return isinstance(response, DownloadResponse)
class BaseDownloadMiddleware(MiddlewareMixin):
def is_download_response(self, response):
return is_download_response(response)
def process_response(self, request, response):
if self.is_download_response(response):
return self.process_download_response(request, response)
return response
def process_download_response(self, request, response):
raise NotImplementedError()
class RealDownloadMiddleware(BaseDownloadMiddleware):
def is_download_response(self, response):
if super(RealDownloadMiddleware, self).is_download_response(response):
try:
return response.file.url or response.file.name
except AttributeError:
return False
else:
return True
return False
## ... source file continues with no further MiddlewareMixin examples...
django-easy-timezones (project website) is a Django middleware code library to simplify handling time data in your applications using users' geolocation data.
django-easy-timezones / easy_timezones / middleware.py
# middleware.py
if not GEOIPV6_DATABASE:
raise ImproperlyConfigured("GEOIPV6_DATABASE setting has not been properly defined.")
if not os.path.exists(GEOIPV6_DATABASE):
raise ImproperlyConfigured("GEOIPV6_DATABASE setting is defined, but file does not exist.")
return (GEOIP_DATABASE, GEOIPV6_DATABASE)
load_db_settings()
def load_db():
GEOIP_DATABASE, GEOIPV6_DATABASE = load_db_settings()
global db
db = pygeoip.GeoIP(GEOIP_DATABASE, pygeoip.MEMORY_CACHE)
global db_v6
db_v6 = pygeoip.GeoIP(GEOIPV6_DATABASE, pygeoip.MEMORY_CACHE)
global db_loaded
db_loaded = True
if django.VERSION >= (1, 10):
from django.utils.deprecation import MiddlewareMixin
middleware_base_class = MiddlewareMixin
else:
middleware_base_class = object
class EasyTimezoneMiddleware(middleware_base_class):
def process_request(self, request):
if not request:
return
if not db_loaded:
load_db()
tz = request.session.get('django_timezone')
if not tz:
tz = timezone.get_default_timezone()
client_ip = get_ip_address_from_request(request)
ip_addrs = client_ip.split(',')
for ip in ip_addrs:
if is_valid_ip(ip) and not is_local_ip(ip):
if ':' in ip:
## ... source file continues with no further MiddlewareMixin examples...
django-oauth-toolkit (project website and PyPI package information) is a code library for adding and handling OAuth2 flows within your Django web application and API.
The django-oauth-toolkit project is open sourced under the FreeBSD license and it is maintained by the developer community group Jazzband.
django-oauth-toolkit / oauth2_provider / middleware.py
# middleware.py
from django.contrib.auth import authenticate
from django.utils.cache import patch_vary_headers
from django.utils.deprecation import MiddlewareMixin
class OAuth2TokenMiddleware(MiddlewareMixin):
def process_request(self, request):
if request.META.get("HTTP_AUTHORIZATION", "").startswith("Bearer"):
if not hasattr(request, "user") or request.user.is_anonymous:
user = authenticate(request=request)
if user:
request.user = request._cached_user = user
def process_response(self, request, response):
patch_vary_headers(response, ("Authorization",))
return response
## ... source file continues with no further MiddlewareMixin examples...
django-pipeline (project documentation and PyPI package information) is a code library for handling and compressing static content assets when handling requests in Django web applications.
The django-pipeline project is open sourced under the MIT License and it is maintained by the developer community group Jazzband.
django-pipeline / pipeline / middleware.py
# middleware.py
from django.core.exceptions import MiddlewareNotUsed
from django.utils.encoding import DjangoUnicodeDecodeError
from django.utils.html import strip_spaces_between_tags as minify_html
from pipeline.conf import settings
from django.utils.deprecation import MiddlewareMixin
class MinifyHTMLMiddleware(MiddlewareMixin):
def __init__(self, *args, **kwargs):
super(MinifyHTMLMiddleware, self).__init__(*args, **kwargs)
if not settings.PIPELINE_ENABLED:
raise MiddlewareNotUsed
def process_response(self, request, response):
if response.has_header('Content-Type') and 'text/html' in response['Content-Type']:
try:
response.content = minify_html(response.content.decode('utf-8').strip())
response['Content-Length'] = str(len(response.content))
except DjangoUnicodeDecodeError:
pass
return response
## ... source file continues with no further MiddlewareMixin examples...
django-webtest (PyPI package information) is a Django extension that makes it easier to use WebTest with your projects.
The project is open sourced under the MIT license.
django-webtest / django_webtest / middleware.py
# middleware.py
import django
from django.contrib.auth.middleware import RemoteUserMiddleware
from django.core.exceptions import ImproperlyConfigured
from django.contrib import auth
if django.VERSION >= (1, 10):
from django.utils.deprecation import MiddlewareMixin
else:
MiddlewareMixin = object
from django_webtest.compat import is_authenticated
class WebtestUserMiddleware(RemoteUserMiddleware):
header = "WEBTEST_USER"
def process_request(self, request):
if not hasattr(request, 'user'):
raise ImproperlyConfigured(
"The django-webtest auth middleware requires the "
"'django.contrib.auth.middleware.AuthenticationMiddleware' "
"to be installed. Add it to your MIDDLEWARE setting "
"or disable django-webtest auth support by setting "
"'setup_auth' property of your WebTest subclass to False."
)
try:
username = request.META[self.header]
except KeyError:
return
if is_authenticated(request.user):
if hasattr(request.user, "get_username"):
authenticated_username = request.user.get_username()
else:
authenticated_username = request.user.username
clean_username = self.clean_username(username, request)
if authenticated_username == clean_username:
return
user = auth.authenticate(django_webtest_user=username)
if user:
request.user = user
auth.login(request, user)
class DisableCSRFCheckMiddleware(MiddlewareMixin):
def process_request(self, request):
request._dont_enforce_csrf_checks = True
## ... source file continues with no further MiddlewareMixin examples...
Graphite (project website, documentation and PyPI package information) is a metrics collection and visualization tool, built with both Python and JavaScript. Metrics are collected by a Node.js application and displayed using a Django web application, called "Graphite-Web", which is one of three core projects under the Graphite umbrella (the other two are Carbon and Whisper).
Graphite is provided as open sourced under the Apache License 2.0.
graphite-web / webapp / graphite / middleware.py
# middleware.py
from graphite.logger import log
try:
from django.utils.deprecation import MiddlewareMixin
except ImportError: # Django < 1.10
MiddlewareMixin = object
class LogExceptionsMiddleware(MiddlewareMixin):
def process_exception(self, request, exception):
log.exception('Exception encountered in <{0} {1}>'.format(request.method, request.build_absolute_uri()))
return None
## ... source file continues with no further MiddlewareMixin examples...
register is a Django, Bootstrap, PostgreSQL project that is open source under the GNU General Public License v3.0. This web application makes it easier for people to register as organ donors. You can see the application live at https://register.organize.org/.
register / registration / middleware.py
# middleware.py
import django.middleware.locale
import django.shortcuts
from django.utils import translation
from django.utils.deprecation import MiddlewareMixin
class RequestLocaleMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
if request.method == 'GET':
language = request.GET.get('lang')
if language:
translation.activate(language)
request.session[translation.LANGUAGE_SESSION_KEY] = translation.get_language()
query = request.GET.copy()
del query['lang']
path = '?'.join([request.path, query.urlencode()])
return django.shortcuts.redirect(path)
## ... source file continues with no further MiddlewareMixin examples...
wagtail (project website) is a fantastic Django-based CMS with code that is open source under the BSD 3-Clause "New" or "Revised" License.
wagtail / wagtail / core / middleware.py
# middleware.py
import warnings
from django.utils.deprecation import MiddlewareMixin
from wagtail.core.models import Site
from wagtail.utils.deprecation import RemovedInWagtail211Warning
warnings.warn(
'wagtail.core.middleware.SiteMiddleware and the use of request.site is deprecated. '
'Please update your code to use Site.find_for_request(request) in place of request.site, '
'and remove wagtail.core.middleware.SiteMiddleware from MIDDLEWARES',
RemovedInWagtail211Warning
)
class SiteMiddleware(MiddlewareMixin):
def process_request(self, request):
try:
request.site = Site.find_for_request(request)
except Site.DoesNotExist:
request.site = None
## ... source file continues with no further MiddlewareMixin examples...