class RickrollPostShowView(View): redirect_url = settings.RICKROLL_URL bot_user_agents = [ re.compile(r'.*TwitterBot.*'), re.compile(r'.*TelegramBot.*'), re.compile(r'.*Twitterbot.*'), re.compile(r'.*bingbot.*'), re.compile(r'.*WhatsApp.*'), re.compile(r'.*Discordbot.*'), re.compile(r'.*bingbot.*'), re.compile(r'.*redditbot.*'), ] @method_decorator(vary_on_headers('User-Agent')) @method_decorator(cache_control(public=True)) def dispatch(self, request: HttpRequest, *args, **kwargs): user_agent = request.META.get('HTTP_USER_AGENT', '') for bot in self.bot_user_agents: if bot.match(user_agent): return self.bots(request, *args, **kwargs) return self.redirect(request, *args, **kwargs) def redirect(self, request, *args, **kwargs): return redirect(self.redirect_url, permanent=True) @method_decorator(cache_page(60 * 60)) def bots(self, request, year, month, day, slug): post = get_object_or_404(RickrollPost, date__year=year, date__month=month, date__day=day, slug=slug) return render(request, 'rickroller/bots.html', {'post': post})
class AWSOrganizationalUnitView(generics.ListAPIView): """API GET list view for AWS organizational units.""" queryset = ( AWSOrganizationalUnit.objects.filter(deleted_timestamp__isnull=True) .annotate(**{"value": F("org_unit_id")}) .values("value") .distinct() ) serializer_class = ResourceTypeSerializer permission_classes = [AWSOUAccessPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value"] search_fields = ["value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): # Reads the users values for org unit id and displays values related to what the user has access to supported_query_params = ["search", "limit"] user_access = [] error_message = {} # Test for only supported query_params if self.request.query_params: for key in self.request.query_params: if key not in supported_query_params: error_message[key] = [{"Unsupported parameter"}] return Response(error_message, status=status.HTTP_400_BAD_REQUEST) if request.user.admin: return super().list(request) elif request.user.access: user_access = request.user.access.get("aws.organizational_unit", {}).get("read", []) if user_access and user_access[0] == "*": return super().list(request) self.queryset = self.queryset.filter(org_unit_id__in=user_access) return super().list(request)
class GetPageDetailsView(BaseDetailView): """ View returns given by url serialized page instance """ model = Page def get(self, request, slug): if request.is_ajax(): page = self.get_object() gateway_ripple_address = RippleWalletCredentials.get_solo().address expiration_minutes = ( GatewaySettings.get_solo().transaction_expiration_minutes) response = { 'page': { 'title': page.title, 'description': page.description.format( gateway_ripple_address=gateway_ripple_address, transaction_expiration_minutes=expiration_minutes, ), }, } return JsonResponse(response, safe=False) return render(request, 'base.html') @method_decorator(ensure_csrf_cookie) @method_decorator(vary_on_headers('X-Requested-With')) def dispatch(self, *args, **kwargs): return super(GetPageDetailsView, self).dispatch(*args, **kwargs)
def as_cached_view(cls, cache_timeout=0, cache_kwargs=None, **initkwargs): """ Calls .as_view() and wraps the result in a cache_page decorator. See https://docs.djangoproject.com/en/1.11/topics/cache/ :param int cache_timeout: same as cache_page; set to 0 for no cache :param dict cache_kwargs: dictionary of kwargs to be passed to cache_page :param initkwargs: kwargs for .as_view() :return: a view instance """ cache_kwargs = cache_kwargs or {} view = cls.as_view(**initkwargs) if cache_timeout != 0: if not public: view = vary_on_headers('Cookie', 'Authorization')(view) view = cache_page(cache_timeout, **cache_kwargs)(view) view = deferred_never_cache(view) # disable in-browser caching elif cache_kwargs: warnings.warn( "cache_kwargs ignored because cache_timeout is 0 (disabled)" ) return view
class CacheListMixin(object): """Cache listed results""" @method_decorator(cache_page(60)) # Ensure that permissions are maintained and not cached! @method_decorator(vary_on_headers("Cookie", "Authorization")) def list(self, *args, **kwargs): return super(CacheListMixin, self).list(*args, **kwargs)
def apply_cache(cls, view, cache_timeout, cache_kwargs): """Override this method to customize how caching is applied to the view. Arguments described in :meth:`.as_cached_view`. """ view = vary_on_headers('Cookie', 'Authorization')(view) view = cache_page(cache_timeout, **cache_kwargs)(view) view = deferred_never_cache(view) # disable in-browser caching return view
class DataViewset(viewsets.ReadOnlyModelViewSet): serializer_class = DailyReportSerializer queryset = DailyReport.objects.all().order_by('date') @method_decorator(cache_page(60 * 5, cache="default_pickle")) @method_decorator(cache_control(public=True, max_age=0, s_maxage=60)) @method_decorator(vary_on_headers('Origin')) def list(self, *args, **kwargs): return super(DataViewset, self).list(*args, **kwargs)
class AWSAccountView(generics.ListAPIView): """API GET list view for AWS accounts.""" queryset = ( AWSCostSummaryByAccountP.objects.annotate( **( { "value": F("usage_account_id"), "alias": Coalesce(F("account_alias__account_alias"), "usage_account_id"), } ) ) .values("value", "alias") .distinct() ) serializer_class = ResourceTypeSerializer permission_classes = [AwsAccessPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value", "alias"] search_fields = ["value", "alias"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): # Reads the users values for aws account and displays values related to what the user has access to. supported_query_params = ["search", "limit", "openshift"] user_access = [] error_message = {} # Test for only supported query_params if self.request.query_params: for key in self.request.query_params: if key not in supported_query_params: error_message[key] = [{"Unsupported parameter"}] return Response(error_message, status=status.HTTP_400_BAD_REQUEST) elif key == "openshift": openshift = self.request.query_params.get("openshift") if openshift == "true": self.queryset = ( OCPAWSCostSummaryByAccountP.objects.annotate( **{ "value": F("usage_account_id"), "alias": Coalesce(F("account_alias__account_alias"), "usage_account_id"), } ) .values("value", "alias") .distinct() ) if request.user.admin: return super().list(request) elif request.user.access: user_access = request.user.access.get("aws.account", {}).get("read", []) if user_access and user_access[0] == "*": return super().list(request) self.queryset = self.queryset.filter(usage_account_id__in=user_access) return super().list(request)
class TagView(ReportView): """Base Tag View.""" report = "tags" @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def get(self, request, **kwargs): """Get Report Data. This method is responsible for passing request data to the reporting APIs. Args: request (Request): The HTTP request object Returns: (Response): The report in a Response object """ LOG.debug(f"API: {request.path} USER: {request.user.username}") key = kwargs.get("key") if key and not self.validate_key(key): raise Http404 try: params = QueryParameters(request=request, caller=self, **kwargs) except ValidationError as exc: return Response(data=exc.detail, status=status.HTTP_400_BAD_REQUEST) if key and params.get("key_only"): LOG.debug("Invalid query parameter 'key_only'.") error = {"details": "Invalid query parameter 'key_only'."} raise ValidationError(error) handler = self.query_handler(params) output = handler.execute_query() if key: output["data"] = [ val for dikt in output.get("data") for val in dikt.get("values") ] max_rank = handler.max_rank paginator = get_paginator(params.parameters.get("filter", {}), max_rank) paginated_result = paginator.paginate_queryset(output, request) LOG.debug(f"DATA: {output}") return paginator.get_paginated_response(paginated_result) def validate_key(self, key): """Validate that tag key exists.""" count = 0 for handler in self.tag_handler: count += handler.objects.filter(key=key).count() return count != 0
class AWSAccountView(generics.ListAPIView): """API GET list view for AWS accounts.""" queryset = AWSCostSummaryByAccount.objects.annotate(**{"value": F("usage_account_id")}).values("value").distinct() serializer_class = ResourceTypeSerializer permission_classes = [ResourceTypeAccessPermission] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): return super().list(request)
class CounterAPIView(GenericAPIView): queryset = Person.objects.all() # pour les permissions permission_classes = (GlobalOnlyPermissions, ) @method_decorator(vary_on_headers("Authorization")) @method_decorator(cache_page(60)) def get(self, request, *args, **kwargs): return Response( {"value": Person.objects.filter(is_2022=True).count()}, status=status.HTTP_200_OK, )
class GCPAccountView(generics.ListAPIView): """API GET list view for GCP accounts.""" queryset = GCPCostSummaryByAccount.objects.annotate(**{"value": F("account_id")}).values("value").distinct() serializer_class = ResourceTypeSerializer permission_classes = [ResourceTypeAccessPermission] filter_backends = [filters.OrderingFilter] ordering = ["value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): return super().list(request)
class ViewSetCacheMixin(object): def list(self, request, *args, **kwargs): sort_by = self.request.query_params.get('sort_by', None) if sort_by is None: return self.cached_list(request, *args, **kwargs) else: return super(ViewSetCacheMixin, self)\ .list(request, *args, **kwargs) @method_decorator(cache_page(60)) @method_decorator(vary_on_headers('Authorization', 'Cookie')) def cached_list(self, request, *args, **kwargs): return super(ViewSetCacheMixin, self)\ .list(request, *args, **kwargs) @method_decorator(cache_page(60)) @method_decorator(vary_on_headers('Authorization', 'Cookie')) def retrieve(self, request, *args, **kwargs): return super(ViewSetCacheMixin, self)\ .retrieve(request, *args, **kwargs)
class OCPClustersView(generics.ListAPIView): """API GET list view for Openshift clusters.""" queryset = OCPCostSummary.objects.annotate(**{"value": F("cluster_id")}).values("value").distinct() serializer_class = ResourceTypeSerializer permission_classes = [ResourceTypeAccessPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value"] search_fields = ["$value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): return super().list(request)
class SingleModelSearch(ListView): prefix = None filterset_class = None paginate_by = 20 @method_decorator(vary_on_headers('X-Requested-With')) def __call__(self, request, **kwargs): super().__call__(request, **kwargs) def get_template_names(self): if self.request.is_ajax(): return ['material/search_ajax.html'] return ['material/search.html'] def get_tabs(self): material_filter = MaterialFilterSet(self.request.GET, prefix='material') activity_filter = ActivityFilterSet(self.request.GET, prefix='activity') reading_filter = ReadingFilterSet(self.request.GET, prefix='reading') video_filter = VideoFilterSet(self.request.GET, prefix='video') link_filter = LinkFilterSet(self.request.GET, prefix='link') return [ (_('All'), reverse('material:search-material'), material_filter.form), (_('Activities'), reverse('material:search-activity'), activity_filter.form), (_('Readings'), reverse('material:search-reading'), reading_filter.form), (_('Videos'), reverse('material:search-video'), video_filter.form), (_('Links'), reverse('material:search-link'), link_filter.form), ] def get_context_data(self, *args, **kwargs): kwargs['show_welcome'] = not self.request.GET kwargs['search_tabs'] = tab_context( update_form(self.get_tabs(), self.get_filterset().form)) return super().get_context_data(*args, **kwargs) def get_filterset(self): return self.filterset_class(self.request.GET, queryset=self.queryset, prefix=self.prefix) def get_queryset(self): filterset = self.get_filterset() query = self.request.GET.get('q') if not query: return filterset.qs return filterset.qs.search(query)
def decorator(func: 'Callable') -> 'Callable': @wraps(func) def inner(request: 'HttpRequest', *args, **kwargs) -> JsonError: if request.method not in allowed_methods: response = JsonError('Method not allowed', 405) response['Allow'] = ', '.join(allowed_methods) log_response( 'Method Not Allowed (%s): %s', request.method, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs) return vary_on_headers('Allow')(inner)
class CostModelResourceTypesView(generics.ListAPIView): """API GET for resource types cost model view.""" queryset = (CostModel.objects.all().annotate( value=Concat("uuid", V(" ("), "name", V(")"), output_field=CharField())).values("value")) serializer_class = ResourceTypeSerializer permission_classes = [ResourceTypeAccessPermission] filter_backends = [filters.OrderingFilter] ordering = ["value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): return super().list(request)
class ArticleViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): """ Final accepted articles, read only view. *Public* """ queryset = Submission.objects.filter( status="accepted").order_by("-date_created") serializer_class = ArticleSerializer permission_classes = [] @method_decorator(cache_page(60 * 2)) @method_decorator(vary_on_cookie) @method_decorator(vary_on_headers("Authorization", )) def list(self, request: Request, *args: Any, **kwargs: Any) -> Response: return super().list(request, *args, **kwargs) @method_decorator(cache_page(60 * 2)) @method_decorator(vary_on_cookie) @method_decorator(vary_on_headers("Authorization", )) def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response: return super().retrieve(request, *args, **kwargs)
class AWSAccountRegionView(generics.ListAPIView): """API GET list view for AWS by region""" queryset = (AWSCostSummaryByRegion.objects.annotate(**{ "value": F("region") }).values("value").distinct().filter(region__isnull=False)) serializer_class = ResourceTypeSerializer permission_classes = [ResourceTypeAccessPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value"] search_fields = ["$value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): return super().list(request)
class ReportView(APIView): """ A shared view for all koku reports. This view maps the serializer based on self.provider and self.report. It providers one GET endpoint for the reports. """ @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def get(self, request, **kwargs): """Get Report Data. This method is responsible for passing request data to the reporting APIs. Args: request (Request): The HTTP request object Returns: (Response): The report in a Response object """ LOG.debug(f"API: {request.path} USER: {request.user.username}") try: params = QueryParameters(request=request, caller=self, **kwargs) except ValidationError as exc: return Response(data=exc.detail, status=status.HTTP_400_BAD_REQUEST) handler = self.query_handler(params) output = handler.execute_query() max_rank = handler.max_rank if "units" in params.parameters: from_unit = _find_unit()(output["data"]) if from_unit: try: to_unit = params.parameters.get("units") unit_converter = UnitConverter() output = _fill_in_missing_units(from_unit)(output) output = _convert_units(unit_converter, output, to_unit) except (DimensionalityError, UndefinedUnitError): error = {"details": _("Unit conversion failed.")} raise ValidationError(error) paginator = get_paginator(params.parameters.get("filter", {}), max_rank) paginated_result = paginator.paginate_queryset(output, request) LOG.debug(f"DATA: {output}") return paginator.get_paginated_response(paginated_result)
class AzureSubscriptionGuidView(generics.ListAPIView): """API GET list view for Azure Subscription Guid.""" queryset = (AzureCostSummaryByAccount.objects.annotate( **{ "value": F("subscription_guid") }).values("value").distinct()) serializer_class = ResourceTypeSerializer permission_classes = [ResourceTypeAccessPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value"] search_fields = ["value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): return super().list(request)
class AWSOrganizationalUnitView(generics.ListAPIView): """API GET list view for AWS organizational units.""" queryset = (AWSOrganizationalUnit.objects.filter( deleted_timestamp__isnull=True).annotate(**{ "value": F("org_unit_id") }).values("value").distinct()) serializer_class = ResourceTypeSerializer permission_classes = [ResourceTypeAccessPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value"] search_fields = ["$value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): return super().list(request)
class GroupViewSet(BaseNslcViewSet): filter_class = GroupFilter serializer_class = GroupSerializer def get_serializer_class(self): if self.action == 'retrieve': return GroupDetailSerializer return self.serializer_class def get_queryset(self): queryset = Group.objects.all() return queryset @method_decorator(cache_page(60 * 10)) @method_decorator(vary_on_headers('Cookie')) def dispatch(self, request, *args, **kwargs): return super().dispatch(request, *args, **kwargs)
class AzureRegionView(generics.ListAPIView): """API GET list view for Azure Region locations.""" queryset = (AzureCostSummaryByLocationP.objects.annotate( **{ "value": F("resource_location") }).values("value").distinct().filter(resource_location__isnull=False)) serializer_class = ResourceTypeSerializer permission_classes = [AzureAccessPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value"] search_fields = ["value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): # Reads the users values for Azure subscription guid and displays values related to what the user has access to supported_query_params = ["search", "limit", "openshift"] user_access = [] error_message = {} # Test for only supported query_params if self.request.query_params: for key in self.request.query_params: if key not in supported_query_params: error_message[key] = [{"Unsupported parameter"}] return Response(error_message, status=status.HTTP_400_BAD_REQUEST) elif key == "openshift": openshift = self.request.query_params.get("openshift") if openshift == "true": self.queryset = ( OCPAzureCostSummaryByLocationP.objects.annotate( **{ "value": F("resource_location") }).values("value").distinct().filter( resource_location__isnull=False)) if request.user.admin: return super().list(request) elif request.user.access: user_access = request.user.access.get("azure.subscription_guid", {}).get("read", []) if user_access and user_access[0] == "*": return super().list(request) self.queryset = self.queryset.filter(subscription_guid__in=user_access) return super().list(request)
def wrapper(view): def wrapped(request, *args, **kwargs): def learn_groups(group): return learn_group_name(group, request, args, kwargs) response = view(request, *args, **kwargs) resp_groups = getattr(response, "cache_groups", []) if not isinstance(resp_groups, list): resp_groups = list(resp_groups) response.cache_groups = map(learn_groups, groups)+resp_groups return response vary = extra.get("vary", ("x-cache-gen",)) if not vary: return wrapped return vary_on_headers(*vary)(wrapped)
class OCPProjectsView(generics.ListAPIView): """API GET list view for Openshift projects.""" queryset = (OCPCostSummaryByProjectP.objects.annotate( **{ "value": F("namespace") }).values("value").distinct().filter(namespace__isnull=False)) serializer_class = ResourceTypeSerializer permission_classes = [ OpenShiftProjectPermission | OpenShiftAccessPermission ] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value"] search_fields = ["value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): # Reads the users values for Openshift projects namespace,displays values related to the users access supported_query_params = ["search", "limit"] error_message = {} query_holder = None # Test for only supported query_params if self.request.query_params: for key in self.request.query_params: if key not in supported_query_params: error_message[key] = [{"Unsupported parameter"}] return Response(error_message, status=status.HTTP_400_BAD_REQUEST) if request.user.admin: return super().list(request) if request.user.access: ocp_project_access = request.user.access.get( "openshift.project", {}).get("read", []) ocp_cluster_access = request.user.access.get( "openshift.cluster", {}).get("read", []) query_holder = self.queryset if ocp_project_access and ocp_project_access[0] != "*": query_holder = query_holder.filter( namespace__in=ocp_project_access) if ocp_cluster_access and ocp_cluster_access[0] != "*": query_holder = query_holder.filter( cluster_id__in=ocp_cluster_access) self.queryset = query_holder return super().list(request)
class GCPServiceView(generics.ListAPIView): """API GET list view for GCP Services by ID.""" queryset = (GCPTopology.objects.annotate(**{ "value": F("service_alias") }).values("value").distinct().filter(service_id__isnull=False)) serializer_class = ResourceTypeSerializer permission_classes = [GcpAccessPermission | GcpProjectPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value"] search_fields = ["value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): # Reads the users values for GCP account id and displays values related to what the user has access to supported_query_params = ["search", "limit"] error_message = {} query_holder = None # Test for only supported query_params if self.request.query_params: for key in self.request.query_params: if key not in supported_query_params: error_message[key] = [{"Unsupported parameter"}] return Response(error_message, status=status.HTTP_400_BAD_REQUEST) if request.user.admin: return super().list(request) if request.user.access: gcp_account_access = request.user.access.get("gcp.account", {}).get("read", []) gcp_project_access = request.user.access.get("gcp.project", {}).get("read", []) # Checks if the access exists, and the user has wildcard access query_holder = self.queryset if gcp_project_access and gcp_project_access[0] != "*": query_holder = query_holder.filter( project_id__in=gcp_project_access) if gcp_account_access and gcp_account_access[0] != "*": query_holder = query_holder.filter( account_id__in=gcp_account_access) self.queryset = query_holder return super().list(request)
def pjax_decorator(view): @functools.wraps(view) def wrapped_view(request, *args, **kwargs): response = view(request, *args, **kwargs) if is_pjax(request): # Before generating a response, strip the "_pjax" GET parameter # that jquery-pjax adds as a browser cache-busting measure. strip_pjax_parameter(request) # This header helps jquery-pjax correctly handle redirects. response['X-PJAX-URL'] = (response.get('Location') or request.get_full_path()) # Test if response supports deferred rendering, approach copied # from django.core.handlers.base.BaseHandler.get_response() if hasattr(response, 'render') and callable(response.render): process_fn(request, response) elif not isinstance(response, HttpResponseRedirect): raise TypeError("PJAX views must return either a response " "with a render() method, or a redirect.") return response return vary_on_headers('X-PJAX-Container')(wrapped_view)
class OCPClustersView(generics.ListAPIView): """API GET list view for Openshift clusters.""" queryset = (OCPCostSummaryP.objects.annotate( **{ "value": F("cluster_id"), "ocp_cluster_alias": Coalesce(F("cluster_alias"), "cluster_id") }).values( "value", "ocp_cluster_alias").distinct().filter(cluster_id__isnull=False)) serializer_class = ResourceTypeSerializer permission_classes = [OpenShiftAccessPermission] filter_backends = [filters.OrderingFilter, filters.SearchFilter] ordering = ["value", "ocp_cluster_alias"] search_fields = ["value", "ocp_cluster_alias"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): # Reads the users values for Openshift cluster id and displays values related to what the user has access to supported_query_params = ["search", "limit"] user_access = None error_message = {} # Test for only supported query_params if self.request.query_params: for key in self.request.query_params: if key not in supported_query_params: error_message[key] = [{"Unsupported parameter"}] return Response(error_message, status=status.HTTP_400_BAD_REQUEST) if request.user.admin: return super().list(request) if request.user.access: user_access = request.user.access.get("openshift.cluster", {}).get("read", []) # checks if the access exists, and the user has wildcard access if user_access and user_access[0] == "*": return super().list(request) self.queryset = self.queryset.filter(cluster_id__in=user_access) return super().list(request)
class SaleListView(APIView, LimitOffsetPagination): authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def post(self, request): serializer = SaleSerializer(data=request.data) if not serializer.is_valid(): return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) org = request.user.org paid = request.data['paid'] identifier = request.data['identifier'] sale = Sale.objects.create(org=org, paid=paid, identifier=identifier) for saledetail in request.data['saledetails']: SaleDetail.objects.create( sale=sale, product_id=saledetail['product_id'], unitprice_id=saledetail['unitprice_id'], amount=saledetail['amount'], discount=saledetail['discount']) serializer = SaleSerializer(sale) return Response(serializer.data) @method_decorator(cache_page(60*10)) @method_decorator(vary_on_headers('Autorization')) @silk_profile(name='Sale list') def get(self, request): queryset = Sale.objects.prefetch_related('saledetails__unitprice').prefetch_related( 'saledetails__product__category').filter(paid=True, org=request.user.org) result_page = self.paginate_queryset(queryset, request, view=self) serializer = SaleSerializer(result_page, many=True) return Response({'sales': serializer.data})
class CostModelResourceTypesView(generics.ListAPIView): """API GET for resource types cost model view.""" queryset = (CostModel.objects.all().annotate( value=Concat("uuid", V(" ("), "name", V(")"), output_field=CharField())).values("value")) serializer_class = ResourceTypeSerializer permission_classes = [CostModelsAccessPermission] filter_backends = [filters.OrderingFilter] ordering = ["value"] @method_decorator(vary_on_headers(CACHE_RH_IDENTITY_HEADER)) def list(self, request): supported_query_params = ["limit"] error_message = {} # Test for only supported query_params if self.request.query_params: for key in self.request.query_params: if key not in supported_query_params: error_message[key] = [{"Unsupported parameter"}] return Response(error_message, status=status.HTTP_400_BAD_REQUEST) return super().list(request)
for f in functions[1:]: result = f(result) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers("Accept-language"), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required("change_world"), # django.contrib.admin.views.decorators staff_member_required, # django.utils.functional allow_lazy, lazy,
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import url, patterns from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_headers from rfdocs.views import (RFTagListViewFilter, RFLibraryListViewFilter, RFLibraryVersionListViewFilter) one_day = 86400 libraries_list_view_filter = url( r'^libraries/', vary_on_headers('X-Requested-With')(cache_page(one_day)(RFLibraryListViewFilter.as_view())), name='libraries_list_filter' ) versions_list_view_filter = url( r'^versions/', vary_on_headers('X-Requested-With')(cache_page(one_day)(RFLibraryVersionListViewFilter.as_view())), name='versions_list_filter' ) tags_list_view_filter = url( r'^tags/', vary_on_headers('X-Requested-With')(cache_page(one_day)(RFTagListViewFilter.as_view())), name='tags_list_filter' ) urlpatterns = patterns('',
urlpatterns += [ path('review', include(wagtailreview_urls)), path('', include(torchbox_urls)), path('graphql/', csrf_exempt(GraphQLView.as_view(graphiql=True))), path('', lambda request: HttpResponseNotFound(), name='home'), ] # Set public URLs to use public cache. urlpatterns = decorate_urlpatterns(urlpatterns, get_default_cache_control_decorator()) # Set vary header to instruct cache to serve different version on different # cookies, different request method (e.g. AJAX) and different protocol # (http vs https). urlpatterns = decorate_urlpatterns( urlpatterns, vary_on_headers('Cookie', 'X-Requested-With', 'X-Forwarded-Proto', 'Accept-Encoding') ) Page.serve = get_default_cache_control_decorator()(Page.serve) # Join private and public URLs. urlpatterns = private_urlpatterns + urlpatterns + decorate_urlpatterns([ # Wagtail paths have to be enabled for the administration interface to work # properly. This allows them to be visited only by the logged-in users to # avoid the public accessing it. path('wagtail/', include(wagtail_urls)) ], login_required)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import url, patterns from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_headers from rfdocs.views import RFKeywordDetailView keyword_detail_view = url( r'^browse/(?P<library_slug>[-\w.]+)/(?P<version_slug>[-\w.]+)/(?P<slug>[-\w\s]+)/$', vary_on_headers('X-Requested-With')(cache_page(86400)(RFKeywordDetailView.as_view())), name='rfkeyword_detail' ) urlpatterns = patterns('django.views.generic.detail', keyword_detail_view)
def fully_decorated(request): """Expected __doc__""" return HttpResponse("<html><body>dummy</body></html>") fully_decorated.anything = "Expected __dict__" # django.views.decorators.http fully_decorated = require_http_methods(["GET"])(fully_decorated) fully_decorated = require_GET(fully_decorated) fully_decorated = require_POST(fully_decorated) # django.views.decorators.vary fully_decorated = vary_on_headers("Accept-language")(fully_decorated) fully_decorated = vary_on_cookie(fully_decorated) # django.views.decorators.cache fully_decorated = cache_page(60 * 15)(fully_decorated) fully_decorated = cache_control(private=True)(fully_decorated) fully_decorated = never_cache(fully_decorated) # django.contrib.auth.decorators fully_decorated = user_passes_test(lambda u: True)(fully_decorated) fully_decorated = login_required(fully_decorated) fully_decorated = permission_required("change_world")(fully_decorated) # django.contrib.admin.views.decorators fully_decorated = staff_member_required(fully_decorated)
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.conf.urls import url, patterns from django.views.decorators.cache import cache_page from django.views.decorators.vary import vary_on_headers from rfdocs.views import RFLibraryVersionDetailView library_version_detail_view = url( r'^browse/(?P<library_slug>[-\w.]+)/(?P<slug>[-\w.]+)/$', vary_on_headers('X-Requested-With')(cache_page(86400)(RFLibraryVersionDetailView.as_view())), name='rflibraryversion_detail' ) urlpatterns = patterns('django.views.generic.detail', library_version_detail_view)
from django.conf.urls.defaults import patterns, url from django.views.decorators.vary import vary_on_headers import view_wrappers from web import views urlpatterns = patterns('', url(r'^$', vary_on_headers('Cookie', 'Accept-Encoding')(view_wrappers.wrap_view(views.main))), )
for f in functions[1:]: result = f(result) return result return _inner full_decorator = compose( # django.views.decorators.http require_http_methods(["GET"]), require_GET, require_POST, require_safe, condition(lambda r: None, lambda r: None), # django.views.decorators.vary vary_on_headers('Accept-language'), vary_on_cookie, # django.views.decorators.cache cache_page(60 * 15), cache_control(private=True), never_cache, # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 user_passes_test(lambda u: True), login_required, permission_required('change_world'), # django.contrib.admin.views.decorators staff_member_required,
url(r'^firetv/', include('podiobooks.firetv.urls')), # Libsyn Utils url(r'^libsyn/', include('podiobooks.libsyn.urls')), # Ratings url(r'^rate/', include('podiobooks.ratings.urls')), # Search url(r'^search/', include('podiobooks.search.urls')), # MUB url(r'^mub/', include('mub.urls')), # Robots, Favicon and Related url(r'^robots\.txt$', vary_on_headers('HOST')(RobotsView.as_view())), url(r'^favicon\.ico$', AccelView.as_view(url='images/favicon.ico')), url(r'^apple-touch-icon\.png$', AccelView.as_view(url=settings.STATIC_URL + 'images/apple-touch-icon.png')), url(r'^humans\.txt$', TextTemplateView.as_view(template_name='humans.txt')), url(r'^crossdomain\.xml', TextTemplateView.as_view(template_name='crossdomain.xml')), # Blog url(r'^blog(?P<url_remainder>.*)', BlogRedirectView.as_view()), # Sitemap url(r'^sitemap\.xml$', sitemap_urls, {'sitemaps': sitemaps}), # PB1 Index Page url(r'index\.php|index\.html', RedirectView.as_view(url='/', permanent=True)), # PB1 Search Redirect
'pol': pol, 'member': pol.latest_member, 'candidacies': pol.candidacy_set.all().order_by('-election__date'), 'electedmembers': pol.electedmember_set.all().order_by('-start_date'), 'page': statement_page, 'statements_politician_view': True, 'show_statements': show_statements, 'activities': activity.iter_recent(Activity.public.filter(politician=pol)), 'search_placeholder': u"Search %s in Parliament" % pol.name }) if request.is_ajax(): t = loader.get_template("hansards/statement_page_politician_view.inc") else: t = loader.get_template("politicians/politician.html") return HttpResponse(t.render(c)) politician = vary_on_headers('X-Requested-With')(PoliticianView.as_view()) def contact(request, pol_id=None, pol_slug=None): if pol_slug: pol = get_object_or_404(Politician, slug=pol_slug) else: pol = get_object_or_404(Politician, pk=pol_id) if not pol.current_member: raise Http404 c = RequestContext(request, { 'pol': pol, 'info': pol.info(), 'title': u'Contact %s' % pol.name
from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required, permission_required, user_passes_test from django.contrib.admin.views.decorators import staff_member_required def fully_decorated(request): """Expected __doc__""" return HttpResponse('<html><body>dummy</body></html>') fully_decorated.anything = "Expected __dict__" # django.views.decorators.http fully_decorated = require_http_methods(["GET"])(fully_decorated) fully_decorated = require_GET(fully_decorated) fully_decorated = require_POST(fully_decorated) # django.views.decorators.vary fully_decorated = vary_on_headers('Accept-language')(fully_decorated) fully_decorated = vary_on_cookie(fully_decorated) # django.views.decorators.cache fully_decorated = cache_page(60*15)(fully_decorated) fully_decorated = cache_control(private=True)(fully_decorated) fully_decorated = never_cache(fully_decorated) # django.contrib.auth.decorators # Apply user_passes_test twice to check #9474 fully_decorated = user_passes_test(lambda u:True)(fully_decorated) fully_decorated = login_required(fully_decorated) fully_decorated = permission_required('change_world')(fully_decorated) # django.contrib.admin.views.decorators fully_decorated = staff_member_required(fully_decorated)
# We don't have request.content_type yet in 2015, # while test client has no META['CONTENT_TYPE']. ct = request.META.get('CONTENT_TYPE', getattr(request, 'content_type', None)) if ct: headers["Content-Type"] = ct if 'HTTP_AUTHORIZATION' in request.META: headers["Authorization"] = request.META['HTTP_AUTHORIZATION'] return { "uri": request.build_absolute_uri(), "http_method": request.method, "body": request.body, "headers": headers, } def oauthlib_response(response_tuple): """Creates a django.http.HttpResponse from (headers, body, status) tuple from OAuthlib.""" headers, body, status = response_tuple response = HttpResponse(body, status=status) for k, v in headers.items(): if k == 'Location': v = iri_to_uri(v) response[k] = v return response vary_on_auth = method_decorator(vary_on_headers('Authorization'), 'dispatch') class HttpResponseAppRedirect(HttpResponseRedirect): allowed_schemes = HttpResponseRedirect.allowed_schemes + ['wolnelekturyapp']
(r'^issue/(?P<pk>\d+)/edit/$', login_required(UpdateView.as_view(model=Issue, success_url="/issue/%(id)d/"))), (r'^issue/(?P<pk>\d+)/$', IssueDetailView.as_view()), url(r'^polity/(?P<polity>\d+)/issues/open/$', IssueOpenListView.as_view(), name='polity_issues_new'), (r'^polity/(?P<polity>\d+)/issue/new/(documentcontent/(?P<documentcontent>\d+)/)?$', login_required(IssueCreateView.as_view())), (r'^search/$', SearchListView.as_view()), (r'^polity/(?P<polity>\d+)/document/$', login_required(DocumentListView.as_view())), (r'^polity/(?P<polity>\d+)/document/new/$', login_required(DocumentCreateView.as_view())), (r'^polity/(?P<polity>\d+)/document/(?P<pk>\d+)/$', DocumentDetailView.as_view()), # (r'^polity/(?P<polity>\d+)/document/(?P<pk>\d+)/edit/$', login_required(DocumentUpdateView.as_view())), (r'^polity/(?P<polity>\d+)/election/$', cache_page(60*1)(vary_on_headers('Cookie')( ElectionListView.as_view()))), (r'^polity/(?P<polity>\d+)/election/new/$', login_required(ElectionCreateView.as_view())), (r'^polity/(?P<polity>\d+)/election/(?P<pk>\d+)/$', ElectionDetailView.as_view()), (r'^polity/(\d+)/election/(?P<pk>\d+)/ballots/$', election_ballots), (r'^polity/(?P<pk>\d+)/edit/$', login_required(UpdateView.as_view(model=Polity, success_url="/polity/%(id)d/"))), (r'^polity/(?P<pk>\d+)/(?P<action>\w+)/$', login_required(PolityDetailView.as_view())), (r'^polity/(?P<pk>\d+)/$', cache_page(60*5)(vary_on_headers('Cookie')( PolityDetailView.as_view()))), (r'^polity/(?P<polity>\d+)/topic/new/$', login_required(TopicCreateView.as_view())), (r'^polity/(?P<polity>\d+)/topic/(?P<pk>\d+)/edit/$', login_required(UpdateView.as_view(model=Topic, success_url="/polity/%(polity__id)d/topic/%(id)d/"))), (r'^polity/(?P<polity>\d+)/topic/(?P<pk>\d+)/$', TopicDetailView.as_view()), # (r'^delegation/(?P<pk>\d+)/$', login_required(DetailView.as_view(model=Delegate, context_object_name="delegation"))),
'page': page, 'allow_single_page': True, 'tab': tab, 'title': ('Bill %s' % bill.number) + (' (Historical)' if bill.session.end else ''), 'statements_full_date': True, 'statements_context_link': True, } if request.is_ajax(): if tab == 'meetings': t = loader.get_template("bills/related_meetings.inc") else: t = loader.get_template("hansards/statement_page.inc") else: t = loader.get_template("bills/bill_detail.html") return HttpResponse(t.render(c, request)) bill = vary_on_headers('X-Requested-With')(BillDetailView.as_view()) class BillListView(ModelListView): resource_name = 'Bills' filters = { 'session': APIFilters.dbfield(help="e.g. 41-1"), 'introduced': APIFilters.dbfield(filter_types=APIFilters.numeric_filters, help="date bill was introduced, e.g. introduced__gt=2010-01-01"), 'legisinfo_id': APIFilters.dbfield(help="integer ID assigned by parl.gc.ca's LEGISinfo"), 'number': APIFilters.dbfield('bill__number', help="a string, not an integer: e.g. C-10"), 'law': APIFilters.dbfield('bill__law', help="did it become law? True, False"), 'private_member_bill': APIFilters.dbfield('bill__privatemember',
def redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None, query=None, vary=None, cache_timeout=12, decorators=None, re_flags=None, to_args=None, to_kwargs=None, prepend_locale=True, merge_query=False): """ Return a url matcher suited for urlpatterns. pattern: the regex against which to match the requested URL. to: either a url name that `reverse` will find, a url that will simply be returned, or a function that will be given the request and url captures, and return the destination. permanent: boolean whether to send a 301 or 302 response. locale_prefix: automatically prepend `pattern` with a regex for an optional locale in the url. This locale (or None) will show up in captured kwargs as 'locale'. anchor: if set it will be appended to the destination url after a '#'. name: if used in a `urls.py` the redirect URL will be available as the name for use in calls to `reverse()`. Does _NOT_ work if used in a `redirects.py` file. query: a dict of query params to add to the destination url. vary: if you used an HTTP header to decide where to send users you should include that header's name in the `vary` arg. cache_timeout: number of hours to cache this redirect. just sets the proper `cache-control` and `expires` headers. decorators: a callable (or list of callables) that will wrap the view used to redirect the user. equivalent to adding a decorator to any other view. re_flags: a string of any of the characters: "iLmsux". Will modify the `pattern` regex based on the documented meaning of the flags (see python re module docs). to_args: a tuple or list of args to pass to reverse if `to` is a url name. to_kwargs: a dict of keyword args to pass to reverse if `to` is a url name. prepend_locale: if true the redirect URL will be prepended with the locale from the requested URL. merge_query: merge the requested query params from the `query` arg with any query params from the request. Usage: urlpatterns = [ redirect(r'projects/$', 'mozorg.product'), redirect(r'^projects/seamonkey$', 'mozorg.product', locale_prefix=False), redirect(r'apps/$', 'https://marketplace.firefox.com'), redirect(r'firefox/$', 'firefox.new', name='firefox'), redirect(r'the/dude$', 'abides', query={'aggression': 'not_stand'}), ] """ if permanent: redirect_class = HttpResponsePermanentRedirect else: redirect_class = HttpResponseRedirect if locale_prefix: pattern = pattern.lstrip('^/') pattern = LOCALE_RE + pattern if re_flags: pattern = '(?{})'.format(re_flags) + pattern view_decorators = [] if cache_timeout is not None: view_decorators.append(cache_control_expires(cache_timeout)) if vary: if isinstance(vary, basestring): vary = [vary] view_decorators.append(vary_on_headers(*vary)) if decorators: if callable(decorators): view_decorators.append(decorators) else: view_decorators.extend(decorators) def _view(request, *args, **kwargs): # don't want to have 'None' in substitutions kwargs = {k: v or '' for k, v in kwargs.items()} args = [x or '' for x in args] # If it's a callable, call it and get the url out. if callable(to): to_value = to(request, *args, **kwargs) else: to_value = to if to_value.startswith('/') or HTTP_RE.match(to_value): redirect_url = to_value else: try: redirect_url = reverse(to_value, args=to_args, kwargs=to_kwargs) except NoReverseMatch: # Assume it's a URL redirect_url = to_value if prepend_locale and redirect_url.startswith('/') and kwargs.get('locale'): redirect_url = '/{locale}' + redirect_url.lstrip('/') # use info from url captures. if args or kwargs: redirect_url = strip_tags(force_text(redirect_url).format(*args, **kwargs)) if query: if merge_query: req_query = parse_qs(request.META.get('QUERY_STRING')) req_query.update(query) querystring = urlencode(req_query, doseq=True) else: querystring = urlencode(query, doseq=True) elif query is None: querystring = request.META.get('QUERY_STRING') else: querystring = '' if querystring: redirect_url = '?'.join([redirect_url, querystring]) if anchor: redirect_url = '#'.join([redirect_url, anchor]) if PROTOCOL_RELATIVE_RE.match(redirect_url): redirect_url = '/' + redirect_url.lstrip('/') return redirect_class(redirect_url) # Apply decorators try: # Decorators should be applied in reverse order so that input # can be sent in the order your would write nested decorators # e.g. dec1(dec2(_view)) -> [dec1, dec2] for decorator in reversed(view_decorators): _view = decorator(_view) except TypeError: log.exception('decorators not iterable or does not contain ' 'callable items') return url(pattern, _view, name=name)
from views import (Login, Logout, Home, Signup, StarRating, StarRatingReport, \ VerifyRecaptcha, AddToWatchlist, AddToComparelist, ViewWatchList, public_login_required,\ ViewCompareList, SearchResult, SearchCompany, DeleteFromCompareList, ChangeCompareList, \ HelpView, ActivateAccount, TermsOfUse, Disclaimer, PrivacyPolicy, FBLoginRedirect, ForgotPassword,\ ResetPassword) LOGIN_URL = '/login/' urlpatterns = patterns('', url(r'^$', Home.as_view(), name="home"), url(r'^fb_login_redirect/$', FBLoginRedirect.as_view(), name="fb_login_redirect"), url(r'^login/$', Login.as_view(), name="public_login"), url(r'^logout/$', Logout.as_view(), name="public_logout"), url(r'^signup/$', Signup.as_view(), name="signup"), url(r'^star_rating/$', public_login_required(vary_on_headers('X_REQUESTED_WITH')(StarRating.as_view()), login_url="/login/"), name="star_rating"), url(r'^star_rating_report/$', public_login_required(vary_on_headers('X_REQUESTED_WITH')(StarRatingReport.as_view()), login_url="/login/"), name="star_rating_report"), url(r'^verify_recaptcha/$', VerifyRecaptcha.as_view(), name="verifiy_recaptcha"), url(r'^add_to_watch_list/$', public_login_required(AddToWatchlist.as_view(), login_url="/login/"), name="add_to_watch_list"), url(r'^add_to_compare_list/$', public_login_required(AddToComparelist.as_view(), login_url="/login/"), name="add_to_compare_list"), url(r'^add_to_compare_list/$', public_login_required(AddToComparelist.as_view(), login_url="/login/"), name="add_to_compare_list"), url(r'^compare_list/$', public_login_required(vary_on_headers('X_REQUESTED_WITH')(ViewCompareList.as_view()), login_url="/login/"), name="compare_list"), url(r'^change_compare_list/$', public_login_required(ChangeCompareList.as_view(), login_url="/login/"), name="change_compare_list"), url(r'^watch_list/$', public_login_required(vary_on_headers('X_REQUESTED_WITH')(ViewWatchList.as_view()), login_url="/login/"), name="watch_list"), url(r'^search_result/$', vary_on_headers('X_REQUESTED_WITH')(SearchResult.as_view()), name="search_result"), url(r'^search_company/$', vary_on_headers('X_REQUESTED_WITH')(SearchCompany.as_view()), name="search_company"), url(r'^delete_from_compare_list/$', public_login_required(DeleteFromCompareList.as_view(), login_url="/login/"), name="delete_from_compare_list"), url(r'^help/$', public_login_required(HelpView.as_view(), login_url="/login/"), name="help"), url(r'^activate/$', ActivateAccount.as_view(), name="activate_account"), url(r'^terms_of_use/$', TermsOfUse.as_view(), name="terms_of_use"), url(r'^disclaimer/$', Disclaimer.as_view(), name="disclaimer"),