def test_with_extra_meta(self): req = self.rf.get('/') for f in getattr( MultipleProxyMiddleware, 'FORWARDED_FOR_FIELDS' ): req.META[f] = 'Value1' del(req.META['HTTP_X_FORWARDED_SERVER']) req.META['HTTP_X_FORWARDED_FOR'] += ',Foo' req.META['SERVER_SOFTWARE'] = 'foo/1.1' viawrap = decorator_from_middleware(ViaHeaderMiddleware) mulwrap = decorator_from_middleware(MultipleProxyMiddleware) viawrap(mulwrap(goodview))(req)
def process_request(self, request): """ Reads url name, args, kwargs from GET parameters, reverses the url and resolves view function Returns the result of resolved view function, called with provided args and kwargs Since the view function is called directly, it isn't ran through middlewares, so the middlewares must be added manually The final result is exactly the same as if the request was for the resolved view. """ if request.path == self.ANGULAR_REVERSE: url_name = request.GET.get('djng_url_name') url_args = request.GET.getlist('djng_url_args', None) url_kwargs = {} # Read kwargs for param in request.GET: if param.startswith('djng_url_kwarg_'): url_kwargs[param[15:]] = request.GET[param] # [15:] to remove 'djng_url_kwarg' prefix url = reverse(url_name, args=url_args, kwargs=url_kwargs, urlconf=self.urlconf) view, args, kwargs = resolve(url, urlconf=self.urlconf) # Set to real path, otherwise this url resolving will be ran again when calling # teh actual view, resulting in infinite recursion request.path = url # Run through all the middlewares when calling actual view # MIDDLEWARE_CLASSES must be reversed to maintain correct order of middlewares execution # (view function is wrapped with middleware decorators, first one added is executed as last) for middleware_path in reversed(settings.MIDDLEWARE_CLASSES): view = decorator_from_middleware(self._import_dotted_path(middleware_path))(view) return view(request, *args, **kwargs)
def append_middleware(urlhandler): "Append TollgateMiddleware to the views." urlhandler.add_prefix('tollgate.frontend.views') urlhandler._callback = decorator_from_middleware( TollgateMiddleware )(urlhandler.callback) return urlhandler
def wrapper(F): class OptionLoader(object): def process_request(self, request): if loader: loader(request) def process_response(self, request, response): if unloader: unloader(request, response) return response return decorator_from_middleware(OptionLoader)(F)
def ssl_view(view): """ Requires that a view be accessed via SSL(HTTPS). Calls to this view where request.is_secure() returns False will redirect to the SSL(HTTPS) version of the view. """ wrapped_view = decorator_from_middleware(SSLMiddleware)(view) # Exempt this view from processing by middleware. wrapped_view.ssl_exempt = True return wrapped_view
def _setup_djangosocket(func): from functools import wraps @wraps(func) def new_func(request, *args, **kwargs): response = func(request, *args, **kwargs) if response is None and request.is_websocket(): return ALREADY_HANDLED return response if not settings.DJANGOSOCKET_MIDDLEWARE_INSTALLED: decorator = decorator_from_middleware(DjangoSocketMiddleware) new_func = decorator(new_func) return new_func
def _setup_websocket(func): from functools import wraps @wraps(func) def new_func(request, *args, **kwargs): response = func(request, *args, **kwargs) if response is None and request.is_websocket(): return HttpResponse() return response if not WEBSOCKET_MIDDLEWARE_INSTALLED: decorator = decorator_from_middleware(WebSocketMiddleware) new_func = decorator(new_func) return new_func
from django.utils.decorators import decorator_from_middleware from lib.ridibooks.ridi_oauth2.middlewares import AuthenticationMiddleware ridi_oauth2_access_token_login = decorator_from_middleware( AuthenticationMiddleware)
super(CustomCacheMiddleware, self).__init__(*args, **kwargs) self.cache_delay = cache_delay def process_response(self, request, response): if self.cache_delay: extra_js = '<script type="text/javascript">var CACHE_CONTROL=%s;</script>' %\ self.cache_delay response.content = response.content.replace( u'</body>', u'%s\n</body>' % extra_js) response = super(CustomCacheMiddleware, self).process_response(request, response) return response custom_cache_page = decorator_from_middleware(CustomCacheMiddleware) if 1 or settings.DEBUG: def cache_page(delay): def rendered(view): def inner(request, *args, **kwargs): return view(request, *args, **kwargs) return inner return rendered custom_cache_page = cache_page
# -*- coding:utf-8 -*- from django.http import HttpResponse from django.utils.decorators import decorator_from_middleware from django.views.generic import View from django.middleware.doc import XViewMiddleware xview_dec = decorator_from_middleware(XViewMiddleware) def xview(request): return HttpResponse() class XViewClass(View): def get(self, request): return HttpResponse()
from functools import wraps from django.views.decorators.cache import cache_page as _django_cache_page from django.utils.decorators import decorator_from_middleware from django_mobile.cache.middleware import FetchFromCacheFlavourMiddleware, UpdateCacheFlavourMiddleware __all__ = ('cache_page', 'vary_on_flavour_fetch', 'vary_on_flavour_update') vary_on_flavour_fetch = decorator_from_middleware(FetchFromCacheFlavourMiddleware) vary_on_flavour_update = decorator_from_middleware(UpdateCacheFlavourMiddleware) def cache_page(*args, **kwargs): ''' Same as django's ``cache_page`` decorator, but wraps the view into additional decorators before and after that. Makes it possible to serve multiple flavours without getting into trouble with django's caching that doesn't know about flavours. ''' decorator = _django_cache_page(*args, **kwargs) def flavoured_decorator(func): return vary_on_flavour_fetch(decorator(vary_on_flavour_update(func))) return flavoured_decorator
from amazonaffiliate.middleware import AmazonAffiliateMiddleware from django.utils.decorators import decorator_from_middleware amazon_affiliate = decorator_from_middleware(AmazonAffiliateMiddleware)
from django.urls import path from django.utils.decorators import decorator_from_middleware from .middleware import StatsMiddleware from .views import HealthCheckView, APIHealthCheckView app_name = "healthcheck" urlpatterns = [ path("check-fe/", decorator_from_middleware(StatsMiddleware)(HealthCheckView.as_view()), name="check-fe"), path("check-api/", decorator_from_middleware(StatsMiddleware)( APIHealthCheckView.as_view()), name="check-api"), ]
from functools import wraps from django.middleware.csrf import CsrfViewMiddleware, get_token from django.utils.decorators import decorator_from_middleware csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds CSRF protection in exactly the same way as CsrfViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient. """ class _EnsureCsrfToken(CsrfViewMiddleware): # We need this to behave just like the CsrfViewMiddleware, but not reject # requests or log warnings. def _reject(self, request, reason): return None requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken) requires_csrf_token.__name__ = 'requires_csrf_token' requires_csrf_token.__doc__ = """ Use this decorator on views that need a correct csrf_token available to RequestContext, but without the CSRF protection that csrf_protect enforces. """ class _EnsureCsrfCookie(CsrfViewMiddleware):
from django.urls import path from django.utils.decorators import decorator_from_middleware from trivia.views import AdminTrivia, cancel_question, AdminTriviaResult from .middleware import AdminCheckMiddleware from .views import (dashboard, TeamsView, delete_team_view, EventsView, delete_event_view, games_view, games_creation_view, game_matches_view, redirect_after_match_update, ImagesView, add_slider_image, remove_slider_image, UsersView, delete_slider_image, game_edit_view, GamesSetting, user_games_view, user_bet_slip, change_user_status, support_view, SupportResponse, SendMessage, game_delete_view, CreditUserAccount, QualifiedPlayers) admin_auth_decorator = decorator_from_middleware(AdminCheckMiddleware) app_name = 'myadmin' urlpatterns = [ path('', dashboard, name='dashboard'), path('teams', admin_auth_decorator(TeamsView.as_view()), name='teams'), path('teams/delete/<int:pk>', admin_auth_decorator(delete_team_view), name='delete_team'), path('events', admin_auth_decorator(EventsView.as_view()), name='events'), path('events/delete/<int:pk>', admin_auth_decorator(delete_event_view), name='delete_event'), path('games', admin_auth_decorator(games_view), name='games'), path('games/setting', admin_auth_decorator(GamesSetting.as_view()), name='games_setting'), path('trivia', admin_auth_decorator(AdminTrivia.as_view()), name='trivia'), path('trivia/result/<int:pk>', admin_auth_decorator(AdminTriviaResult.as_view()), name='trivia_result'), path('trivia/cancel/<int:pk>', admin_auth_decorator(cancel_question), name='trivia_cancel'), path('games/create', admin_auth_decorator(games_creation_view), name='games_create'), path('games/matches/<int:pk>', admin_auth_decorator(game_matches_view), name='game_matches'), path('games/edit/<int:pk>', admin_auth_decorator(game_edit_view), name='edit_game'), path('games/delete/<int:pk>', admin_auth_decorator(game_delete_view), name='delete_game'), path('games/matches/update/success/<int:pk>', admin_auth_decorator(redirect_after_match_update)), path('images', admin_auth_decorator(ImagesView.as_view()), name='images'),
from django.utils.decorators import decorator_from_middleware from audit_log.middleware import UserLoggingMiddleware log_current_user = decorator_from_middleware(UserLoggingMiddleware)
import logging from django.conf import settings from django.utils.decorators import decorator_from_middleware, decorator_from_middleware_with_args from cache.middleware import CacheFlavourRequestMiddleware, CacheFlavourResponseMiddleware, ResilientCacheMiddleware __all__ = ('cache_page', 'vary_on_flavour_request', 'vary_on_flavour_response') vary_on_flavour_request = decorator_from_middleware(CacheFlavourRequestMiddleware) vary_on_flavour_response = decorator_from_middleware(CacheFlavourResponseMiddleware) logger = logging.getLogger('%s.%s' % (getattr(settings, 'LOG_ROOT'), __name__)) def cache_page(*args, **kwargs): def flavoured_decorator(func): return vary_on_flavour_request(_cache_page(*args, **kwargs)(vary_on_flavour_response(func))) return flavoured_decorator def _cache_page(*args, **kwargs): """ Copied almost everything from the original except replacing the middleware. """ # We also add some asserts to give better error messages in case people are # using other ways to call cache_page that no longer work. if len(args) != 1 or callable(args[0]): raise TypeError("cache_page has a single mandatory positional argument: timeout") cache_timeout = args[0]
import time from django.utils.decorators import decorator_from_middleware from django.utils.deprecation import MiddlewareMixin class StatsMiddleware(MiddlewareMixin): def process_request(self, request): """ Start time at request coming in """ request.start_time = time.time() def process_response(self, request, response): """ End of request, take time """ total = time.time() - request.start_time # Add the header. response["X-Response-Time-Duration-ms"] = int(total * 1000) return response stats = decorator_from_middleware(StatsMiddleware)
from django.http import HttpResponse from django.middleware.doc import XViewMiddleware from django.template import Template, Context from django.template.response import TemplateResponse from django.test import TestCase, RequestFactory from django.utils.decorators import decorator_from_middleware xview_dec = decorator_from_middleware(XViewMiddleware) @xview_dec def xview(request): return HttpResponse() class ClassXView(object): def __call__(self, request): return HttpResponse() class_xview = xview_dec(ClassXView()) class FullMiddleware(object): def process_request(self, request): request.process_request_reached = True def process_view(sef, request, view_func, view_args, view_kwargs): request.process_view_reached = True def process_template_response(self, request, response):
def via_header(view_func): return decorator_from_middleware( import_string('headers.middleware.ViaHeaderMiddleware') )(view_func)
from django.utils.decorators import decorator_from_middleware class _EnsureCsrfCookie(CsrfViewMiddleware): def _reject(self, request, reason): return None def process_view(self, request, callback, callback_args, callback_kwargs): retval = super(_EnsureCsrfCookie, self).process_view(request, callback, callback_args, callback_kwargs) # Forces process_response to send the cookie get_token(request) return retval ensure_csrf_cookie = decorator_from_middleware(_EnsureCsrfCookie) ensure_csrf_cookie.__name__ = 'ensure_csrf_cookie' ensure_csrf_cookie.__doc__ = """ Use this decorator to ensure that a view sets a CSRF cookie, whether or not it uses the csrf_token template tag, or the CsrfViewMiddleware is used. """ class NexusSite(object): def __init__(self, name=None, app_name='nexus'): self._registry = {} self._categories = SortedDict() if name is None: self.name = 'nexus' else: self.name = name
from functools import wraps from django.utils.decorators import available_attrs, decorator_from_middleware from .middleware import get_middleware_class http_auth_protect = decorator_from_middleware(get_middleware_class()) http_auth_protect.__name__ = 'http_auth_protect' def http_auth_exempt(view_func): def wrapped_view(*args, **kwargs): return view_func(*args, **kwargs) wrapped_view.http_auth_exempt = True return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
# load the json data data = json.loads(request.body) request.POST = json_to_query_set(data) if request.method == 'GET' and 'data' in request.GET: data = json.loads(request.GET['data']) request.GET = json_to_query_set(data) return None def __init__(self, get_response): self._get_response = get_response def __call__(self, request): self.process_request(request) return self._get_response(request) class AngelMiddleware: def process_request(self, request): if 'angel_id' in request.session: request.angel = Angel.objects.get(pk=request.session['angel_id']) return None else: return JsonResponse({ 'success': False, 'message': 'not log in', }) with_angel = decorator_from_middleware(AngelMiddleware)
from django.views.decorators.csrf import CsrfViewMiddleware from django.middleware.csrf import get_token from django.utils.decorators import decorator_from_middleware class _EnsureCsrfCookie(CsrfViewMiddleware): def _reject(self, request, reason): return None def process_view(self, request, callback, callback_args, callback_kwargs): retval = super(_EnsureCsrfCookie, self).process_view(request, callback, callback_args, callback_kwargs) # Forces process_response to send the cookie get_token(request) return retval ensure_csrf_cookie = decorator_from_middleware(_EnsureCsrfCookie) ensure_csrf_cookie.__name__ = 'ensure_csrf_cookie' ensure_csrf_cookie.__doc__ = """ Use this decorator to ensure that a view sets a CSRF cookie, whether or not it uses the csrf_token template tag, or the CsrfViewMiddleware is used. """ class NexusSite(object): def __init__(self, name=None, app_name='nexus'): self._registry = {} self._categories = SortedDict() if name is None: self.name = 'nexus' else: self.name = name
from django.middleware.csrf import CsrfViewMiddleware from django.utils.decorators import decorator_from_middleware, available_attrs try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds CSRF protection in exactly the same way as CsrfViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient. """ class _EnsureCsrfToken(CsrfViewMiddleware): # We need this to behave just like the CsrfViewMiddleware, but not reject # requests. def _reject(self, request, reason): return None requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken) requires_csrf_token.__name__ = 'requires_csrf_token' csrf_protect.__doc__ = """ Use this decorator on views that need a correct csrf_token available to RequestContext, but without the CSRF protection that csrf_protect enforces. """
return self.error_500(request, e) return response def default_error_404(self, request): return Response('A 404 error occurred', status=404) def default_error_500(self, request, e): return Response('A 500 error occurred: %r' % e, status=505) ########NEW FILE######## __FILENAME__ = middleware from django.utils.decorators import decorator_from_middleware from django.middleware.gzip import GZipMiddleware GZip = decorator_from_middleware(GZipMiddleware) del GZipMiddleware ########NEW FILE######## __FILENAME__ = response from django.http import HttpResponse as HttpResponseOld from Cookie import SimpleCookie class Response(HttpResponseOld): _charset = 'utf8' def __init__(self, content='', status=None, content_type=None): if not content_type: content_type = 'text/html; charset=%s' % self._charset if not isinstance(content, basestring) and\ hasattr(content, '__iter__'):
def get_decorator_tuple(decorators, middleware_classes): middleware_classes = [decorator_from_middleware(import_if_string(middleware_class)) for middleware_class in middleware_classes or []] decorators = [import_if_string(decorator) for decorator in decorators or []] return tuple(middleware_classes + decorators)[::-1]
class BasicAuthMiddleware(object): def unauthed(self): response = HttpResponse('Error: Authentication required', mimetype="text/plain") response['WWW-Authenticate'] = 'Basic realm="NHSD API"' response.status_code = 401 return response def process_request(self, request): # REMOTE_USER might be set by Apache or other proxies that have already # authenticated, if they did it via basic auth for our username, we # assume that's ok if request.META.get('AUTH_TYPE') == 'Basic' and request.META.get('REMOTE_USER') == settings.API_BASICAUTH_USERNAME: return None elif not 'HTTP_AUTHORIZATION' in request.META: return self.unauthed() else: authentication = request.META['HTTP_AUTHORIZATION'] (authmeth, auth) = authentication.split(' ', 1) if 'basic' != authmeth.lower(): return self.unauthed() auth = auth.strip().decode('base64') username, password = auth.split(':', 1) if username == settings.API_BASICAUTH_USERNAME and password == settings.API_BASICAUTH_PASSWORD: return None return self.unauthed() basic_auth = decorator_from_middleware(BasicAuthMiddleware)
import imp import django from django.test import TestCase from django.test.client import RequestFactory from django.utils.decorators import decorator_from_middleware from django.http import HttpResponse, HttpResponseNotFound from django.core import urlresolvers from django.contrib.auth.models import AnonymousUser from django.conf.urls import include, url, patterns from widgy.contrib.urlconf_include.middleware import PatchUrlconfMiddleware from widgy.contrib.urlconf_include.models import UrlconfIncludePage patch_decorator = decorator_from_middleware(PatchUrlconfMiddleware) @patch_decorator def plain_view(request): return HttpResponse('') @patch_decorator def view_that_resolves(request, login_url): # Use request.urlconf because we're mocking everything. BaseHandler # would call set_urlconf if we were making a real request. from django.contrib.auth.views import login as login_view match = urlresolvers.resolve(login_url, request.urlconf) assert match.func == login_view return HttpResponse('')
example, as that is unique across a Django project. Additionally, all headers from the response's Vary header will be taken into account on caching -- just like the middleware does. """ try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.3, 2.4 fallback. from django.utils.decorators import decorator_from_middleware from django.utils.cache import patch_cache_control, add_never_cache_headers from django.middleware.cache import CacheMiddleware cache_page = decorator_from_middleware(CacheMiddleware) def cache_control(**kwargs): def _cache_controller(viewfunc): def _cache_controlled(request, *args, **kw): response = viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response return wraps(viewfunc)(_cache_controlled) return _cache_controller def never_cache(view_func):
def update_context(self, user, sender, instance, **kwargs): registry = FieldRegistry() if sender in registry: for field in registry.get_fields(sender): if field.one_time and getattr(instance, field.name, None): continue if isinstance(field, CurrentUserField): setattr(instance, field.name, user) def process_response(self, request, response): signals.pre_save.disconnect(dispatch_uid=request) return response record_current_context = decorator_from_middleware(CurrentUserMiddleware) class CurrentUserField(models.ForeignKey): def __init__(self, one_time = False, **kwargs): self.one_time = one_time super(CurrentUserField, self).__init__(get_user_model(), null=True, **kwargs) def contribute_to_class(self, cls, name): super(CurrentUserField, self).contribute_to_class(cls, name) registry = FieldRegistry() registry.add_field(cls, self) try: from south.modelsinspector import add_introspection_rules
def as_view(cls, *args, **kwargs): view = super(RequestLogViewMixin, cls).as_view(*args, **kwargs) view = decorator_from_middleware(RequestLogMiddleware)(view) return view
from django.views.decorators.csrf import csrf_exempt from drf_yasg import openapi from drf_yasg.utils import swagger_auto_schema from metagov.core import utils from metagov.core.app import MetagovApp from metagov.core.handlers import MetagovRequestHandler from metagov.core.middleware import CommunityMiddleware from metagov.core.models import Community, Plugin, ProcessStatus from metagov.core.plugin_manager import plugin_registry from metagov.core.serializers import CommunitySerializer, GovernanceProcessSerializer, PluginSerializer from rest_framework import status from rest_framework.decorators import api_view from rest_framework.exceptions import APIException, ValidationError from rest_framework.parsers import JSONParser community_middleware = decorator_from_middleware(CommunityMiddleware) logger = logging.getLogger(__name__) metagov_app = MetagovApp() metagov_handler = MetagovRequestHandler(app=metagov_app) # FIXME: it feels like this should be in HTTPWrapper but might a Django-based driver want a # convenience method for accessing schemas? @swagger_auto_schema(**MetagovSchemas.plugin_metadata) @api_view(["GET"]) def plugin_metadata(request, plugin_name): cls = plugin_registry.get(plugin_name) if not cls: return HttpResponseBadRequest(f"No such plugin: {plugin_name}")
authenticator = authentication_class() try: user_auth_tuple = authenticator.authenticate(r) if user_auth_tuple is not None: user, auth = user_auth_tuple return user except (ObjectDoesNotExist, exceptions.AuthenticationFailed) as e: logger.debug(e) continue except exceptions.APIException: raise return None authorization = decorator_from_middleware(AuthorizationMiddleware) @authorization def _get_user(request): return request.user def get_scope_user(scope): if "_cached_user" not in scope: # We need to fake a request so the auth code works scope['method'] = "FAKE" from channels.http import AsgiRequest fake_request = AsgiRequest(scope, b'') fake_request.session = scope["session"]
from django.utils.decorators import decorator_from_middleware from minimar.pytrack.middleware import TrackVisitorMiddleware track_visitor = decorator_from_middleware(TrackVisitorMiddleware)
def add_webmention_headers_to_response(request, response): link_header = '<{scheme}://{host}{path}>; rel="webmention"'.format( scheme=request.scheme, host=request.META.get("HTTP_HOST"), path=reverse("webmention:receive")) if not response.get("Link"): response["Link"] = link_header else: response["Link"] = ", ".join((response["Link"], link_header)) return response class WebMentionMiddleware(object): def process_response(self, request, response): return add_webmention_headers_to_response(request, response) def webmention_middleware(get_response): def middleware(request): response = get_response(request) return add_webmention_headers_to_response(request, response) return middleware include_webmention_information = decorator_from_middleware( WebMentionMiddleware)
from django.http import HttpRequest from django.utils.cache import get_cache_key from django.utils.decorators import decorator_from_middleware from view_cache_utils.middleware import CacheMiddleware ''' decorator for advanced view caching ''' try: # django svn >= rev. 11586 from django.utils.decorators import decorator_from_middleware_with_args def cache_page_with_prefix(*args, **kwargs): return decorator_from_middleware_with_args(CacheMiddleware)(*args) except ImportError: # django svn < rev. 11586, django 1.0, 1.1 cache_page_with_prefix = decorator_from_middleware(CacheMiddleware) def expire_page(path, key_prefix=None): ''' Delete page from cache based on it's url ''' request = HttpRequest() request.path = path key = get_cache_key(request, key_prefix) if cache.has_key(key): cache.delete(key) def expire_pages(path, key_prefixes): '''
from django.middleware.csrf import CsrfViewMiddleware from django.utils.decorators import decorator_from_middleware, available_attrs try: from functools import wraps except ImportError: from django.utils.functional import wraps # Python 2.4 fallback. csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds CSRF protection in exactly the same way as CsrfViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient. """ def csrf_response_exempt(view_func): """ Modifies a view function so that its response is exempt from the post-processing of the CSRF middleware. """ def wrapped_view(*args, **kwargs): resp = view_func(*args, **kwargs) resp.csrf_exempt = True return resp return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view) def csrf_view_exempt(view_func): """ Marks a view function as being exempt from CSRF view protection. """
from django.utils.decorators import decorator_from_middleware from django.middleware.gzip import GZipMiddleware gzip_page = decorator_from_middleware(GZipMiddleware) gzip_page.__doc__ = "Decorator for views that gzips pages if the client supports it."
from django.http import HttpResponse from django.template import engines from django.template.response import TemplateResponse from django.test import RequestFactory, SimpleTestCase from django.utils.decorators import classproperty, decorator_from_middleware class ProcessViewMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): pass process_view_dec = decorator_from_middleware(ProcessViewMiddleware) @process_view_dec def process_view(request): return HttpResponse() class ClassProcessView(object): def __call__(self, request): return HttpResponse() class_process_view = process_view_dec(ClassProcessView()) class FullMiddleware(object): def process_request(self, request): request.process_request_reached = True
from django.utils.decorators import decorator_from_middleware from middleware import AnalyticsMiddleware analytics = decorator_from_middleware(AnalyticsMiddleware)
def __init__(self, value=None): self.value = value if value is None: self.value = HEADER_VALUE if not self.value: raise MiddlewareNotUsed def process_response(self, request, response): response_ct = response.get('Content-Type','').split(';', 1)[0].lower() if response_ct in CONTENT_TYPES: if not 'X-UA-Compatible' in response: response['X-UA-Compatible'] = self.value return response xuacompatible = decorator_from_middleware(XUACompatibleMiddleware) # Strip Google Analytics cookies for caching middleware purposes # From http://djangosnippets.org/snippets/1772/ # Author: nf / [email protected] import re class StripCookieMiddleware(object): strip_re = re.compile(r'(__utm.=.+?(?:; |$))') def process_request(self, request): try: cookie = self.strip_re.sub('', request.META['HTTP_COOKIE']) request.META['HTTP_COOKIE'] = cookie except: pass
# encoding: utf-8 from django.middleware.gzip import GZipMiddleware from django.utils.decorators import decorator_from_middleware gzip_page = decorator_from_middleware(GZipMiddleware) gzip_page.__doc__ = "Decorator for views that gzips pages if the client supports it."
# -*- coding: utf-8 -*- from functools import wraps from django.utils.decorators import decorator_from_middleware from debreach.middleware import RandomCommentMiddleware append_random_comment = decorator_from_middleware(RandomCommentMiddleware) append_random_comment.__name__ = str('append_random_comment') append_random_comment.__doc__ = ''' Applies a random comment to the response of the decorated view in the same way as the RandomCommentMiddleware. Using both, or using the decorator multiple times is harmless and efficient. ''' def random_comment_exempt(view_func): """ Marks a view as being exempt from having its response modified by the RandomCommentMiddleware """ def wrapped_view(*args, **kwargs): response = view_func(*args, **kwargs) response._random_comment_exempt = True return response return wraps(view_func)(wrapped_view)
class TwitchAuth(LoginRequiredMixin, UserMixin, generic.View): csrf_protect = decorator_from_middleware(CsrfViewMiddlewareTwitch) @method_decorator(csrf_protect) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def get(self, request): if self.user.active_race_entrant: messages.error( self.request, 'Sorry, you cannot change your Twitch account whilst entered ' 'in an active race.') else: code = request.GET.get('code') if code: user = self.user user.twitch_code = code try: token = user.twitch_access_token(request) resp = requests.get('https://api.twitch.tv/helix/users', headers={ 'Authorization': f'Bearer {token}', 'Client-ID': settings.TWITCH_CLIENT_ID, }) if resp.status_code != 200: raise requests.RequestException except requests.RequestException as ex: notice_exception(ex) messages.error( request, 'Something went wrong with the Twitch API. Please try ' 'again later', ) else: try: data = resp.json().get('data').pop() except: data = {} if models.User.objects.filter( twitch_id=data.get('id'), ).exclude( id=user.id).exists(): messages.error( request, 'Your Twitch account is already connected to another ' 'racetime.gg user account.', ) else: user.twitch_id = data.get('id') user.twitch_name = data.get('display_name') user.save() user.log_action('twitch_auth', self.request) messages.success( self.request, 'Thanks, you have successfully authorized your Twitch.tv ' 'account. You can now join races that requires streaming.', ) return http.HttpResponseRedirect(reverse('edit_account_connections'))
from django.views.decorators.cache import cache_page as _cache_page from django.utils.decorators import decorator_from_middleware from .middleware import XFlavourMiddleware vary_on_flavour = decorator_from_middleware(XFlavourMiddleware) def cache_page(*args, **kwargs): """ Same as django's ``cache_page`` decorator, but wraps the view into ``vary_on_flavour`` decorator before. Makes it possible to serve multiple flavours without getting into trouble with django's caching that doesn't know about flavours. """ decorator = _cache_page(*args, **kwargs) def flavoured_decorator(func): return decorator(vary_on_flavour(func)) return flavoured_decorator
from django.urls import path from admin.middleware import AdminCheckMiddleware from .views import index_view, QuestionView, entries_view, entry_view from utilities.general_middleware import AuthCheckLoginMiddleware from django.utils.decorators import decorator_from_middleware user_auth_decorator = decorator_from_middleware(AuthCheckLoginMiddleware) admin_auth_decorator = decorator_from_middleware(AdminCheckMiddleware) app_name = 'trivia' urlpatterns = [ path('', index_view, name='index'), path('question/<int:pk>', user_auth_decorator(QuestionView.as_view()), name='question'), path('entries', user_auth_decorator(entries_view), name='entries'), path('entries/<int:pk>', user_auth_decorator(entry_view), name='entry'), # path('api/create-match', admin_auth_decorator(QuestionApiView.as_view())), ]
def testCreateInitialRevisionsSpecificModels(self): call_command("createinitialrevisions", "auth.ReversionTestModel1") self.assertEqual(Revision.objects.count(), 2) self.assertEqual(Version.objects.count(), 2) call_command("createinitialrevisions", "auth.ReversionTestModel2") self.assertEqual(Revision.objects.count(), 4) self.assertEqual(Version.objects.count(), 4) def testCreateInitialRevisionsSpecificComment(self): call_command("createinitialrevisions", comment="Foo bar") self.assertEqual(Revision.objects.all()[0].comment, "Foo bar") # Tests for reversion functionality that's tied to requests. revision_middleware_decorator = decorator_from_middleware(RevisionMiddleware) # A dumb view that saves a revision. @revision_middleware_decorator def save_revision_view(request): ReversionTestModel1.objects.create( name = "model1 instance3 version1", ) ReversionTestModel1.objects.create( name = "model1 instance4 version1", ) ReversionTestModel2.objects.create( name = "model2 instance3 version1", ) ReversionTestModel2.objects.create( name = "model2 instance4 version1",
# settings option to configure which headers should # not be processed # ------------------------------ # # if request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): # # This request shouldn't update anythiong, # # so no signal handler should be attached # return if hasattr(request, 'user') and request.user.is_authenticated(): user = request.user else: user = None update_users = curry(self.update_users, user) signals.pre_save.connect(update_users, dispatch_uid=request, weak=False) def update_users(self, user, sender, instance, **kwargs): registry = registration.FieldRegistry() if sender in registry: for field in registry.get_fields(sender): setattr(instance, field.name, user) def process_response(self, request, response): signals.pre_save.disconnect(dispatch_uid=request) return response record_current_user = decorator_from_middleware(CurrentUserMiddleware)
""" Decorators for views based on HTTP headers. """ from calendar import timegm from datetime import timedelta from functools import wraps from django.utils.decorators import decorator_from_middleware, available_attrs from django.utils.http import http_date, parse_http_date_safe, parse_etags, quote_etag from django.utils.log import getLogger from django.middleware.http import ConditionalGetMiddleware from django.http import HttpResponseNotAllowed, HttpResponseNotModified, HttpResponse conditional_page = decorator_from_middleware(ConditionalGetMiddleware) logger = getLogger('django.request') def require_http_methods(request_method_list): """ Decorator to make a view only accept particular request methods. Usage:: @require_http_methods(["GET", "POST"]) def my_view(request): # I can assume now that only GET or POST requests make it this far # ... Note that request methods should be in uppercase. """ def decorator(func):
except Exception, e: return self.error_500(request, e) return response def default_error_404(self, request): return Response('A 404 error occurred', status=404) def default_error_500(self, request, e): return Response('A 500 error occurred: %r' % e, status=505) ########NEW FILE######## __FILENAME__ = middleware from django.utils.decorators import decorator_from_middleware from django.middleware.gzip import GZipMiddleware GZip = decorator_from_middleware(GZipMiddleware) del GZipMiddleware ########NEW FILE######## __FILENAME__ = response from django.http import HttpResponse as HttpResponseOld from Cookie import SimpleCookie class Response(HttpResponseOld): _charset = 'utf8' def __init__(self, content='', status=None, content_type=None): if not content_type: content_type = 'text/html; charset=%s' % self._charset if not isinstance(content, basestring) and\ hasattr(content, '__iter__'): self._container = content self._is_string = False
from django.utils.decorators import decorator_from_middleware from prodjango.current_user import registration class CurrentUserMiddleware(object): def process_request(self, request): if request.method in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): # This request shouldn't update anything, # so no singal handler should be attached. return if hasattr(request, 'user') and request.user.is_authenticated(): user = request.user else: user = None update_users = curry(self.update_users, user) signals.pre_save.connect(update_users, dispatch_uid=request, weak=False) def update_users(self, user, sender, instance, **kwargs): registry = registration.FieldRegistry() if sender in registry: for field in registry.get_fields(sender): setattr(instance, field.name, user) def process_response(self, request, response): signals.pre_save.disconnect(dispatch_uid=request) return response record_current_user = decorator_from_middleware(CurrentUserMiddleware)
from django.http import HttpResponse from django.template import Template, Context from django.template.response import TemplateResponse from django.test import TestCase, RequestFactory from django.utils.decorators import decorator_from_middleware class ProcessViewMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): pass process_view_dec = decorator_from_middleware(ProcessViewMiddleware) @process_view_dec def process_view(request): return HttpResponse() class ClassProcessView(object): def __call__(self, request): return HttpResponse() class_process_view = process_view_dec(ClassProcessView()) class FullMiddleware(object): def process_request(self, request): request.process_request_reached = True def process_view(sef, request, view_func, view_args, view_kwargs):
from django.utils.decorators import decorator_from_middleware from django.middleware.http import ConditionalGetMiddleware from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.core.exceptions import ObjectDoesNotExist from django.core.validators import * from django.db.models.functions import TruncMonth, TruncDay from api.models import Crash, Storage, Fuzzer, OnetimeUrl from accounts.models import Profile from django.db.models import Count from django.utils.timezone import now from datetime import datetime, timedelta from functools import wraps import hashlib conditional_page = decorator_from_middleware(ConditionalGetMiddleware) def apikey_required_do(stub): """ Decorator to check 'api key' contains in HTTP Header. """ def decorator(func): @wraps(func) def inner(request, *args, **kwargs): result = {"result": False, "message": None} if "HTTP_APIKEY" not in request.META: result['message'] = get_error_msg('wrong_apikey') return JsonResponse(result) return func(request, *args, **kwargs) return inner
if not constant_time_compare(request_csrf_token, csrf_token): if cookie_is_new: # probably a problem setting the CSRF cookie logger.warning('Forbidden (%s): %s' % (REASON_NO_CSRF_COOKIE, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_NO_CSRF_COOKIE) else: logger.warning('Forbidden (%s): %s' % (REASON_BAD_TOKEN, request.path), extra={ 'status_code': 403, 'request': request, } ) return self._reject(request, REASON_BAD_TOKEN) return self._accept(request) csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds CSRF protection in exactly the same way as CsrfViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient. """
# Copyright (c) 2015 Intel Corporation. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from django.utils.decorators import decorator_from_middleware from github_webhooks.middleware import PayloadMiddleware from github_webhooks.middleware import SignatureMiddleware add_github_payload = decorator_from_middleware(PayloadMiddleware) require_github_signature = decorator_from_middleware(SignatureMiddleware)