示例#1
0
def record_thumbnail(request, id, name):
    force_reprocess = request.GET.get('reprocess') == 'true'
    filename = get_thumbnail_for_record(id,
                                        request.user,
                                        crop_to_square='square' in request.GET,
                                        force_reprocess=force_reprocess)
    if filename:
        Activity.objects.create(
            event='media-thumbnail',
            request=request,
            content_type=ContentType.objects.get_for_model(Record),
            object_id=id,
            data=dict(square=int('square' in request.GET)))
        try:
            response = HttpResponse(content=open(filename, 'rb').read(),
                                    content_type='image/jpeg')
            patch_cache_control(response, private=True, max_age=3600)
            return response
        except IOError:
            logging.error("IOError: %s" % filename)

    response = HttpResponseRedirect(
        reverse('static', args=('images/thumbnail_unavailable.png', )))
    patch_cache_control(response, no_cache=True)
    return response
示例#2
0
    def retrieve(self, request, *args, **kwargs):
        width = request.GET.get('width')
        height = request.GET.get('height')
        zoom = request.GET.get('zoom')

        if zoom:
            zoom = int(zoom)

        rotation = request.GET.get('rotation')

        if rotation:
            rotation = int(rotation)

        task = task_generate_document_page_image.apply_async(
            kwargs=dict(document_page_id=self.get_object().pk,
                        width=width,
                        height=height,
                        zoom=zoom,
                        rotation=rotation))

        cache_filename = task.get(timeout=DOCUMENT_IMAGE_TASK_TIMEOUT)
        with storage_documentimagecache.open(cache_filename) as file_object:
            response = HttpResponse(file_object.read(), content_type='image')
            if '_hash' in request.GET:
                patch_cache_control(
                    response,
                    max_age=settings_document_page_image_cache_time.value)
            return response
示例#3
0
    def middleware(request: Request):
        public_headers = {
            'public': True,
            'max-age': 60 * 5,
            'stale-while-revalidate': 60 * 5,
            'stale-if-error': (60 * 60) * 24,
        }

        private_headers = {
            'private': True,
            'max-age': 0,
            'must-revalidate': True,
        }

        response = get_response(request)

        if not response.get('Cache-Control'):
            if request.META.get(settings.AUTHORIZATION_PREVIEW_HEADER, False):
                cache_headers = private_headers
            else:
                cache_headers = public_headers

            patch_cache_control(response, **cache_headers)

        return response
示例#4
0
    def post(self, request):
        response = HttpResponse()
        name = cache.get('my_key')
        response.write("<h2>{name}</h2>".format(name=name))
        patch_cache_control(response, private=True)  # 私有缓存控制 2

        return response
示例#5
0
	def process_response(self, request, response):
		for pair in settings.CACHE_CONTROL:
			if re.search(pair[0], request.path):
				response['Cache-Control'] = ""
				patch_cache_control(response, **pair[1])
				break
		return response
示例#6
0
    def render_to_response(self, context, **response_kwargs):
        response = super(LogViewer,
                         self).render_to_response(context, **response_kwargs)

        has_next_page = False
        if self.request.is_ajax():
            # easily parsed with Javascript
            if self.next_page:
                response['X-NextPage'] = self.next_page
                has_next_page = True

            if self.prev_page:
                response['X-PrevPage'] = self.prev_page
        else:
            # Official SEO header
            links = []
            if self.next_page:
                links.append('{0}; rel="next"'.format(self.next_page))
                has_next_page = True

            if self.prev_page:
                links.append('{0}; rel="prev"'.format(self.prev_page))
            response['Link'] = ','.join(links)
        response['X-Timezone'] = self.timezone
        if has_next_page and self.request.user.is_anonymous():
            patch_cache_control(response,
                                public=True,
                                max_age=settings.CACHE_MIDDLEWARE_SECONDS)
        else:
            patch_cache_control(response, private=True)
        return response
示例#7
0
def index(request):

    auth_form = forms.AuthForm(
        request.GET or None,
        prefix="auth",
    )

    if request.GET and auth_form.is_valid():
        try:
            authenticate(request, auth_form.cleaned_data["pnr"])
            return redirect(guest_details)
        except models.Group.DoesNotExist:
            auth_form.add_error("pnr", "This confirmation code is invalid.")

    data = {
        "auth_form": auth_form,
        "body_class": "home",
    }

    response = render(request, "wedding/index.html", data)
    if request.GET:
        patch_cache_control(response, private=True, max_age=60)
    else:
        patch_cache_control(response, public=True, max_age=3600)
    return response
示例#8
0
def generic_institute(request, *args, **kwargs):
    level = 'institute'
    institute = kwargs.get('institute', '')
    category = kwargs.get('category', '')
    subcategory = kwargs.get('subcategory', '')

    is_authorized = auth.is_authorized(sciper=request.user.sciper,
                                       section=level,
                                       sub_section=institute,
                                       category=category)
    if not is_authorized:
        raise PermissionDenied()

    context = {
        'tableau_base_url': settings.TABLEAU_BASE_URL,
        'level': 'institute',
        'institute': institute,
        'category': category,
        'subcategory': subcategory
    }

    if subcategory:
        template_path = 'dashboard/institute/{}/{}.html'.format(
            category, subcategory)
    else:
        template_path = 'dashboard/{}/{}.html'.format(level, category)

    response = render(request, template_path, context=context)
    patch_cache_control(response, private=True)
    return response
示例#9
0
def dispatch(request, page_id=None, node=None, url=None):
    if page_id is not None:
        page = get_object_or_404(Page, pk=page_id)
    else:
        page = None

    if page and settings.DEBUG:
        if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE")
        if if_modified_since:
            if_modified_since = parse_http_date_safe(if_modified_since)
            res_last_modified = timegm(page.last_modified.utctimetuple())
            logger.debug('page="%d", if-last-modified="%s", '
                         'last-modified="%s"', page_id,
                         http_date(if_modified_since),
                         http_date(res_last_modified))

    base = 'touchtechnology/content'
    args = url.split('/')
    templates = list(template_path(
        base, '%s.html' % (page and 'page' or 'folder'), *args))

    if page and page.template:
        templates.insert(0, page.template)

    context = {
        'page': page,
        'node': node,
    }
    response = TemplateResponse(request, templates, context)

    # For authenticated visitors we may alter the rendered content, so mark
    # the content as private to stop interim caches from keeping a copy.
    if request.user.is_authenticated:
        patch_cache_control(response, private=True)
    return response
示例#10
0
    def render_to_response(self, context, **response_kwargs):
        response = super(LogViewer, self).render_to_response(
            context, **response_kwargs)

        has_next_page = False
        if self.format == 'html':
            # Official SEO header
            links = []
            if self.next_page:
                links.append('{0}; rel="next"'.format(self.next_page))
                has_next_page = True

            if self.prev_page:
                links.append('{0}; rel="prev"'.format(self.prev_page))
            response['Link'] = ','.join(links)
        else:
            # No HTML, pass page info in easily parseable headers
            if self.next_page:
                response['X-NextPage'] = self.next_page
                has_next_page = True

            if self.prev_page:
                response['X-PrevPage'] = self.prev_page

        if has_next_page and self.request.user.is_anonymous():
            patch_cache_control(
                response, public=True,
                max_age=settings.CACHE_MIDDLEWARE_SECONDS)
        else:
            patch_cache_control(response, private=True)
        return response
示例#11
0
    def process_request(self, request):
        """Process request and redirect user if they're unauthenticated."""
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if path == '':
                return
            if not any(m.match(path) for m in EXEMPT_URLS):
                if request.is_ajax():
                    # For AJAX requests, return a 400 (which will trigger
                    # jquery's ajax error functionality) and include the error
                    # in a way consistent with the rest of Connect. This is to
                    # prevent AJAX requests from ever being sent through the
                    # login flow (which can cause problems.)
                    response = HttpResponseBadRequest(
                        json.dumps({
                            'success': False,
                            'errors': [
                                'You Must Be Logged In',
                            ]
                        }),
                        content_type='application/json'
                    )
                else:
                    redirect_to = '%s?next=%s' % (settings.LOGIN_URL,
                                                  request.path_info)
                    response = HttpResponseRedirect(redirect_to)

                # Break the client-side cache on all possible browsers on all
                # protocols.
                patch_cache_control(
                    response, no_cache=True, no_store=True,
                    must_revalidate=True, max_age=0, private=True,
                    proxy_revalidate=True, s_maxage=0)
                return response
示例#12
0
    def __init__(self, request, template, *args, **kwargs):

        super(DrinkStaticTemplateResponse, self).__init__(request, template, *args, **kwargs)

        patch_cache_control(
            self, public=True,
            max_age=settings.PUBLIC_CACHE_TIME,
        )
示例#13
0
 def wrapper(*args, **kwargs):
     response = decorated_function(*args, **kwargs)
     patch_cache_control(response,
                         no_cache=True,
                         no_store=True,
                         must_revalidate=True,
                         max_age=0)
     return response
示例#14
0
文件: mixins.py 项目: cash2one/source
 def dispatch(self, request, *args, **kwargs):
     response = super(CacheControlMixin,
                      self).dispatch(request, *args, **kwargs)
     cache_control = self.cache_control.copy()
     if 'private' not in cache_control and 'public' not in cache_control:
         key = 'public' if request.user.is_anonymous() else 'private'
         cache_control[key] = True
     patch_cache_control(response, **cache_control)
     return response
示例#15
0
def homepage(request):
    def tagorder(c: Chal):
        s = c.tags_str()
        return 0 if 'welcoming' in s else \
                1 if 'good_first_challenge' in s else \
                2 if 'intro' in s else 3

    own_private_chals = Chal.objects.filter(owner_user__id=request.user.id,
                                            public_checkout=None)
    grp_private_chals = Chal.objects.filter(owner_group__in=request.user.groups.all(), public_checkout=None)\
            .exclude(owner_user__id=request.user.id)
    if request.user.is_authenticated:
        # Also see the profile page
        us = get_settings(request.user)

        public_chals = list(Chal.objects.filter(public_checkout__isnull=False)\
                .exclude(solved_by=us).order_by('points', '-format', 'name'))
        # First push zero-points to the end
        public_chals.sort(key=lambda c: 1 if (c.points == 0) else 0)
        # Reorder: welcoming, good_first_challenge, intro
        public_chals.sort(key=tagorder)

        solved_chals = Chal.objects.filter(public_checkout__isnull=False,
                                           solved_by=us).order_by(
                                               '-points', '-format', 'name')
        own_achievements = us.achievements.all()
        other_achievements = Achievement.objects.exclude(
            pk__in=own_achievements)
        own_vms = VM.objects.filter(creation_user=request.user,
                                    deleted=False).order_by('-id')
    else:
        public_chals = list(Chal.objects.filter(public_checkout__isnull=False)\
                .order_by('points', '-format', 'name'))
        # First push zero-points to the end
        public_chals.sort(key=lambda c: 1 if (c.points == 0) else 0)
        # Reorder: welcoming, good_first_challenge, intro
        public_chals.sort(key=tagorder)
        solved_chals = []
        own_achievements = []
        other_achievements = Achievement.objects.all()
        own_vms = []
    response = render(
        request, 'ctfoood/home.html', {
            "own_private_chals": own_private_chals,
            "grp_private_chals": grp_private_chals,
            "public_chals": public_chals,
            "solved_chals": solved_chals,
            "own_achievements": own_achievements,
            "other_achievements": other_achievements,
            "own_vms": own_vms,
        })
    if request.user.is_authenticated:
        patch_cache_control(response, max_age=0, must_revalidate=True)
    else:
        patch_cache_control(response, max_age=1800)
    return response
示例#16
0
def fetch_query_results(request, name):
    if request.method == "OPTIONS":
        response = HttpResponse(status=204)
    else:
        if name == "single_card_details" and \
         "HTTP_X_TWITCH_EXTENSION_VERSION" not in request.META:
            # 2017-01-18 emergency fix
            return HttpResponse(status=204)

        parameterized_query = _get_query_and_params(request, name)
        if issubclass(parameterized_query.__class__, HttpResponse):
            return parameterized_query

        last_modified = parameterized_query.result_as_of
        if last_modified:
            last_modified = timegm(last_modified.utctimetuple())

        response = None

        is_cache_hit = parameterized_query.result_available
        if is_cache_hit:
            _trigger_if_stale(parameterized_query)
            # Try to return a minimal response
            response = get_conditional_response(request,
                                                last_modified=last_modified)

        if not response:
            if request.method == "HEAD":
                response = HttpResponse(204)
            else:
                # Resort to a full response
                response = _fetch_query_results(parameterized_query,
                                                user=request.user)

        # Add Last-Modified header
        if response.status_code in (200, 204, 304):
            response["Last-Modified"] = http_date(last_modified)

        # Add Cache-Control headers
        if parameterized_query.is_personalized or parameterized_query.has_premium_values:
            patch_cache_control(response, no_cache=True, private=True)
        else:
            patch_cache_control(response, no_cache=True, public=True)

    # Add CORS header if permitted - can be replaced by middleware in future
    origin = urlparse(request.META.get("HTTP_ORIGIN", ""))
    if origin.netloc in settings.ANALYTICS_CORS_ORIGIN_WHITELIST:
        response["Access-Control-Allow-Origin"] = origin.geturl()
        response["Access-Control-Allow-Methods"] = "GET, HEAD, OPTIONS"
        response["Access-Control-Allow-Headers"] = ", ".join(
            settings.ANALYTICS_CORS_HEADER_WHITELIST)

    # Always patch vary header so browsers do not cache CORS
    patch_vary_headers(response, ["Origin"])

    return response
示例#17
0
    def r(request, *args, **kwargs):
        if not request.user.is_authenticated():
            redirect_url = reverse('logged_out_json')
            response = HttpResponseRedirect(redirect_url)
        else:
            response = f(request, *args, **kwargs)

        patch_cache_control(response, private=True, no_cache=True, no_store=True, must_revalidate=True)
        add_never_cache_headers(response)
        return(response)
示例#18
0
def ping(request):
    response = HttpResponse('pong', status=200)
    patch_cache_control(
        response, **{
            'must-revalidate': True,
            'no-cache': True,
            'no-store': True,
            'private': True,
        })
    return response
示例#19
0
        def wrap(request, *args, **kwargs):
            response = None
            if hub_mode and '/RaceDB/Hub' not in request.path:
                # If hub mode, default to hub search page.
                response = HttpResponseRedirect(
                    '/RaceDB/Hub/SearchCompetitions/')
            elif request.user.username == 'serve' and not selfserve_ok:
                # If self-serve, reject page that is not self-serve.
                response = HttpResponseRedirect('/RaceDB/SelfServe')
            elif not hub_mode and not request.user.is_superuser:
                # Unless superuser, cannot access a competition in the past.
                competition = None
                if 'competitionId' in kwargs:
                    competition = Competition.objects.filter(
                        id=kwargs['competitionId']).first()
                elif 'participantId' in kwargs:
                    participant = Participant.objects.filter(
                        id=kwargs['participantId']).defer(
                            'signature').select_related('competition').first()
                    if participant:
                        competition = participant.competition
                elif 'eventId' in kwargs and 'eventType' in kwargs:
                    try:
                        eventType = int(kwargs['eventType'])
                    except:
                        eventType = -1
                    if eventType == 0:
                        event = EventMassStart.objects.filter(
                            id=kwargs['eventId']).select_related(
                                'competition').first()
                    elif eventType == 1:
                        event = EventTT.objects.filter(
                            id=kwargs['eventId']).select_related(
                                'competition').first()
                    else:
                        event = None
                    if event:
                        competition = event.competition

                if competition and competition.is_finished():
                    response = HttpResponseRedirect('/RaceDB/PastCompetition')

            response = response or decorated_func(request, *args, **kwargs)

            if no_cache:
                patch_cache_control(
                    response,
                    no_cache=True,
                    no_store=True,
                    must_revalidate=True,
                    proxy_revalidate=True,
                    max_age=0,
                )
                response['Pragma'] = 'no-cache'
            return response
示例#20
0
def index(request):
    numbers = [randint(1,9) for x in range(0,10)]

    response = render_to_response('random_app/index.html',
                              {'numbers': numbers,
                               },
                              context_instance=RequestContext(request))

    #response['Cache-Control'] = 'no-cache'
    patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True, max_age=60)
    return response
示例#21
0
def index(request):
    context = {
        'image_relative_path':
        'dashboard/img/myKompas.png',
        'title':
        'School of Engineering',
        'details':
        "You will find your statistics within the School of Engineering.",
    }
    response = render(request, 'generic_section_page.html', context=context)
    patch_cache_control(response, private=True)
    return response
示例#22
0
    def retrieve(self, request, *args, **kwargs):
        task = task_generate_workflow_image.apply_async(
            kwargs=dict(document_state_id=self.get_object().pk, ))

        cache_filename = task.get(timeout=WORKFLOW_IMAGE_TASK_TIMEOUT)
        cache_file = self.get_object().cache_partition.get_file(
            filename=cache_filename)
        with cache_file.open() as file_object:
            response = HttpResponse(file_object.read(), content_type='image')
            if '_hash' in request.GET:
                patch_cache_control(
                    response, max_age=settings_workflow_image_cache_time.value)
            return response
示例#23
0
def index(request):
    numbers = [randint(1, 9) for x in range(0, 10)]

    response = render_to_response('random_app/index.html', {
        'numbers': numbers,
    },
                                  context_instance=RequestContext(request))

    #response['Cache-Control'] = 'no-cache'
    patch_cache_control(response,
                        no_cache=True,
                        no_store=True,
                        must_revalidate=True,
                        max_age=60)
    return response
示例#24
0
    def get(self, request, **kwargs):
        serializer = self.serializer_class(data=request.GET)
        serializer.is_valid(raise_exception=True)

        supplied_params = request.GET.copy()
        supplied_params.update(serializer.validated_data)
        del supplied_params["query"]
        if "Region" in supplied_params:
            supplied_params["Region"] = Region.from_int(
                supplied_params["Region"]).name

        try:
            parameterized_query = serializer.query.build_full_params(
                supplied_params)
        except InvalidOrMissingQueryParameterError as e:
            raise PermissionDenied(str(e)) from e

        if parameterized_query.has_premium_values:
            if not self._check_premium(request):
                raise PermissionDenied("You do not have access to this query.")

        last_modified = parameterized_query.result_as_of
        if last_modified:
            last_modified = timegm(last_modified.utctimetuple())

        response = None

        is_cache_hit = parameterized_query.result_available
        if is_cache_hit:
            _trigger_if_stale(parameterized_query)
            # Try to return a minimal response
            response = get_conditional_response(request,
                                                last_modified=last_modified)

        if not response:
            # Resort to a full response
            response = _fetch_query_results(parameterized_query,
                                            user=request.user)

        response["last-modified"] = http_date(last_modified)

        # Always send Cache-Control headers
        if parameterized_query.is_personalized or parameterized_query.has_premium_values:
            patch_cache_control(response, no_cache=True, private=True)
        else:
            patch_cache_control(response, no_cache=True, public=True)

        return response
示例#25
0
    def __call__(self, request):
        headers = {
            'public': True,
            'max-age': 60 * 5,  # 5 minutes, 300 seconds
            'stale-while-revalidate': 60 * 5,  # 5 minutes, 300 seconds
            'stale-if-error': (60 * 60) * 24,  # 1 day, 86400 seconds
        }

        response = self.get_response(request)

        # skip patching cache headers if already explicitly set
        if 'Cache-Control' not in response:
            patch_cache_control(response, **headers)

        patch_vary_headers(response, ['Accept'])

        return response
示例#26
0
def register(request):
    if request.method=="GET":
        form = RolnikForm()
    if request.method == 'POST':
        form=RolnikForm(request.POST)
        if form.is_valid():
            email=form.cleaned_data['email']
            password=form.cleaned_data['password1']
            rolnik=form.save(commit=False)
            UserModel().objects.create_user(email, email, password)
            rolnik.user=authenticate(username=email, password=password)
            rolnik.save()
            login(request, rolnik.user)
            return redirect('rolnicy-mojprofil')
    response = render_to_response('registration/registration_form.html', context_instance=RequestContext(request,{'form':form}))
    patch_cache_control(response, no_cache=True, no_store=True, must_revalidate=True)
    return response
示例#27
0
文件: middleware.py 项目: amr/dnsman
    def process_request(self, request):
        for domain in Domain.objects.exclude(parking_page=None):
            if domain.match_request(request) and domain.parking_page.match_request(request):
                response = domain.parking_page.to_response(request, domain)
                
                patch_cache_control(response, no_cache=True, max_age=0)
                
                # Expires in the past to force no caching with HTTP/1.0 caches which do
                # not recognize cache-control.
                response['Expires'] = http_date(time.time() - 86400)

                # If Varnish integration is active, we permit Varnish to cache our response
                # despite the expires and cache-control headers.
                if settings.VARNISH_INTEGRATION:
                    from dnsman.varnish_integration.cache import varnish_can_cache
                    varnish_can_cache(response)

                return response
示例#28
0
文件: middleware.py 项目: amr/dnsman
    def process_request(self, request):
        for redirection in Redirection.objects.filter(enabled=True).order_by('-weight'):
            if redirection.match_request(request):
                response = redirection.to_response(request)

                patch_cache_control(response, no_cache=True, max_age=0)

                # Expires in the past to force no caching with HTTP/1.0 caches which do
                # not recognize cache-control.
                response['Expires'] = http_date(time.time() - 86400)

                # If Varnish integration is active, we permit Varnish to cache our response
                # despite the expires and cache-control headers.
                if settings.VARNISH_INTEGRATION:
                    from dnsman.varnish_integration.cache import varnish_can_cache
                    varnish_can_cache(response)

                return response
示例#29
0
    def retrieve(self, request, *args, **kwargs):
        width = request.GET.get('width')
        height = request.GET.get('height')
        zoom = request.GET.get('zoom')

        if zoom:
            zoom = int(zoom)

        rotation = request.GET.get('rotation')

        if rotation:
            rotation = int(rotation)

        maximum_layer_order = request.GET.get('maximum_layer_order')
        if maximum_layer_order:
            maximum_layer_order = int(maximum_layer_order)

        task = task_generate_document_page_image.apply_async(
            kwargs=dict(document_page_id=self.get_object().pk,
                        width=width,
                        height=height,
                        zoom=zoom,
                        rotation=rotation,
                        maximum_layer_order=maximum_layer_order,
                        user_id=request.user.pk))

        kwargs = {'timeout': DOCUMENT_IMAGE_TASK_TIMEOUT}
        if settings.DEBUG:
            # In debug more, task are run synchronously, causing this method
            # to be called inside another task. Disable the check of nested
            # tasks when using debug mode.
            kwargs['disable_sync_subtasks'] = False

        cache_filename = task.get(**kwargs)
        cache_file = self.get_object().cache_partition.get_file(
            filename=cache_filename)
        with cache_file.open() as file_object:
            response = HttpResponse(file_object.read(), content_type='image')
            if '_hash' in request.GET:
                patch_cache_control(
                    response=response,
                    max_age=settings_document_page_image_cache_time.value)
            return response
示例#30
0
    def process_request(self, request):
        for domain in Domain.objects.exclude(parking_page=None):
            if domain.match_request(
                    request) and domain.parking_page.match_request(request):
                response = domain.parking_page.to_response(request, domain)

                patch_cache_control(response, no_cache=True, max_age=0)

                # Expires in the past to force no caching with HTTP/1.0 caches which do
                # not recognize cache-control.
                response['Expires'] = http_date(time.time() - 86400)

                # If Varnish integration is active, we permit Varnish to cache our response
                # despite the expires and cache-control headers.
                if settings.VARNISH_INTEGRATION:
                    from dnsman.varnish_integration.cache import varnish_can_cache
                    varnish_can_cache(response)

                return response
示例#31
0
    def render(self, request, templates, context, tz=None, **kwargs):
        logger.debug(
            "{app}.render: {request.path}".format(
                app=self.__class__.__name__, request=request
            )
        )
        context.update({"application": self})
        kwargs.setdefault("context", context)

        response = TemplateResponse(request, templates, **kwargs)
        response.current_app = self.current_app

        if tz is not None:
            with timezone.override(tz):
                response.render()

        if not request.user.is_anonymous:
            patch_cache_control(response, private=True)
        return response
示例#32
0
    def retrieve(self, request, *args, **kwargs):
        task = task_generate_workflow_image.apply_async(
            kwargs=dict(document_state_id=self.get_object().pk, ))

        kwargs = {'timeout': WORKFLOW_IMAGE_TASK_TIMEOUT}
        if settings.DEBUG:
            # In debug more, task are run synchronously, causing this method
            # to be called inside another task. Disable the check of nested
            # tasks when using debug mode.
            kwargs['disable_sync_subtasks'] = False

        cache_filename = task.get(**kwargs)
        cache_file = self.get_object().cache_partition.get_file(
            filename=cache_filename)
        with cache_file.open() as file_object:
            response = HttpResponse(file_object.read(), content_type='image')
            if '_hash' in request.GET:
                patch_cache_control(
                    response, max_age=settings_workflow_image_cache_time.value)
            return response
示例#33
0
文件: files.py 项目: hachacha/janeway
def serve_file_to_browser(file_path,
                          file_to_serve,
                          public=False,
                          hide_name=False):
    """ Stream a file to the browser in a safe way

    :param file_path: the path on disk to the file
    :param file_to_serve: the core.models.File object to serve
    :param public: boolean
    :param hide_name: boolean
    :return: HttpStreamingResponse object
    """
    # stream the response to the browser
    # we use the UUID filename to avoid any security risks of putting user content in headers
    # we set a chunk size of 8192 so that the entire file isn't loaded into memory if it's large
    filename, extension = os.path.splitext(file_to_serve.original_filename)

    if file_to_serve.mime_type in IMAGE_MIMETYPES:
        response = HttpResponse(
            FileWrapper(open(file_path, 'rb'), 8192),
            content_type=file_to_serve.mime_type,
        )
        patch_cache_control(response, max_age=600)
    else:
        response = StreamingHttpResponse(FileWrapper(open(file_path, 'rb'),
                                                     8192),
                                         content_type=file_to_serve.mime_type)

    response['Content-Length'] = os.path.getsize(file_path)
    if public:
        response['Content-Disposition'] = 'attachment; filename="{0}"'.format(
            file_to_serve.public_download_name())
    elif hide_name:
        response['Content-Disposition'] = 'attachment; filename="{0}"'.format(
            file_to_serve.uuid_filename, )
    else:
        response[
            'Content-Disposition'] = 'attachment; filename="{0}{1}"'.format(
                slugify(filename), extension)

    return response
示例#34
0
def utm_redirect(request, pk, source=None, medium=None, name=None):
    try:
        content = Content.objects.get(pk=pk)
    except Content.DoesNotExist:
        # should really just return whatever handler404 is here
        response = TemplateResponse(request, "404.html", {}, status=404)
        patch_cache_control(response, no_cache=True)
        return response

    content_url = content.get_absolute_url()

    # UTM Tracking only works if all three are present...
    if source and medium and name:
        query_string = urlencode({
            "utm_source": utm_source.get(source, "none"),
            "utm_medium": utm_medium.get(medium, "none"),
            "utm_campaign": utm_campaign.get("utm_campaign", "default")
        })
        content_url = "{}?{}".format(content_url, query_string)

    return HttpResponsePermanentRedirect(content_url)
    def process_response(self, request, response):
        """
        Add 'Cache-Control' and 'Expires' HTTP headers to responses.

        CACHE_MAX_AGE tells the user's browser how many seconds it can
        serve the cached representation without having to check with the
        origin server.

        CACHE_SHARED_MAX_AGE is the same as CACHE_MAX_AGE, but it applies
        to public caches.

        The 'Expires' HTTP header is added for completeness, though
        'Cache-Control' has been adopted pretty much everywhere and is the
        HTTP/1.1 standard.
        """
        params = dict(
            max_age = CACHE_MAX_AGE,
            s_maxage = CACHE_SHARED_MAX_AGE,
        )
        patch_cache_control(response, **params)
        response['Expires'] = http_date(time.time() + CACHE_MAX_AGE)
        return response
    def process_response(self, request, response):
        """
        Add 'Cache-Control' and 'Expires' HTTP headers to responses.

        CACHE_MAX_AGE tells the user's browser how many seconds it can
        serve the cached representation without having to check with the
        origin server.

        CACHE_SHARED_MAX_AGE is the same as CACHE_MAX_AGE, but it applies
        to public caches.

        The 'Expires' HTTP header is added for completeness, though
        'Cache-Control' has been adopted pretty much everywhere and is the
        HTTP/1.1 standard.
        """
        params = dict(
            max_age=CACHE_MAX_AGE,
            s_maxage=CACHE_SHARED_MAX_AGE,
        )
        patch_cache_control(response, **params)
        response['Expires'] = http_date(time.time() + CACHE_MAX_AGE)
        return response
示例#37
0
def generic_faculty(request, *args, **kwargs):
    level = 'faculty'
    role = kwargs.get('role', '')
    category = kwargs.get('category', '')
    subcategory = kwargs.get('subcategory', '')

    if role == 'dean':
        is_authorized = auth.is_authorized(sciper=request.user.sciper,
                                           section=level,
                                           category=category)
    elif role == "associate-dean":
        is_authorized = auth.is_authorized(sciper=request.user.sciper,
                                           section=role,
                                           category=category)
    else:
        is_authorized = auth.is_authorized(sciper=request.user.sciper,
                                           section=level,
                                           category=category)
    if not is_authorized:
        raise PermissionDenied()

    context = {
        'tableau_base_url': settings.TABLEAU_BASE_URL,
        'level': level,
        'role': role,
        'category': category,
        'subcategory': subcategory
    }

    if subcategory:
        template_path = 'dashboard/faculty/{}/{}/{}.html'.format(
            role, category, subcategory)
    else:
        template_path = 'dashboard/faculty/{}/{}.html'.format(role, category)

    response = render(request, template_path, context=context)
    patch_cache_control(response, private=True)

    return response
示例#38
0
    def __call__(self, request):
        public_headers = {
            'public': True,
            'max-age': 60 * 5, # 5 minutes, 300 seconds
            'stale-while-revalidate': 60 * 5, # 5 minutes, 300 seconds
            'stale-if-error': (60 * 60) * 24, # 1 day, 86400 seconds
        }
        private_headers = {
            'private': True,
            'max-age': 0, # seconds
            'must-revalidate': True,
        }

        authenticated = request.META[settings.KONG_AUTH_HEADER]
        headers = public_headers if not authenticated else private_headers

        response = self.get_response(request)

        if not response.get('Cache-Control'):
            patch_cache_control(response, **headers)
        patch_vary_headers(response, ['Accept'])

        return response
示例#39
0
def generic_personal(request, *args, **kwargs):
    level = 'personal'
    sciper = kwargs.get('sciper', '')
    category = kwargs.get('category', '')
    subcategory = kwargs.get('subcategory', '')

    is_authorized = auth.is_authorized(sciper=request.user.sciper,
                                       section=level,
                                       category=category)
    if not is_authorized:
        raise PermissionDenied()

    # prevent users to access other people information
    if sciper != str(request.user.sciper):
        raise PermissionDenied()

    institute = epfl_ldap.get_institute(
        sciper, official_institutes=settings.STI_INSTITUTES)

    context = {
        'tableau_base_url': settings.TABLEAU_BASE_URL,
        'level': 'personal',
        'sciper': sciper,
        'category': category,
        'subcategory': subcategory,
        'institute': institute,
    }

    if subcategory:
        template_path = 'dashboard/personal/{}/{}.html'.format(
            category, subcategory)
    else:
        template_path = 'dashboard/personal/{}.html'.format(category)

    response = render(request, template_path, context)
    patch_cache_control(response, private=True)
    return response
示例#40
0
def utm_redirect(request, pk, source=None, medium=None, name=None):
    try:
        content = Content.objects.get(pk=pk)
    except Content.DoesNotExist:
        # should really just return whatever handler404 is here
        response = TemplateResponse(request, "404.html", {}, status=404)
        patch_cache_control(response, no_cache=True)
        return response

    content_url = content.get_absolute_url()

    # UTM Tracking only works if all three are present...
    if source and medium and name:
        query_string = urlencode({
            "utm_source":
            utm_source.get(source, "none"),
            "utm_medium":
            utm_medium.get(medium, "none"),
            "utm_campaign":
            utm_campaign.get("utm_campaign", "default")
        })
        content_url = "{}?{}".format(content_url, query_string)

    return HttpResponsePermanentRedirect(content_url)
示例#41
0
 def wrapper(*args, **kwargs):
     response = decorated_method(*args, **kwargs)
     patch_cache_control(
         response, no_cache=True, no_store=True, must_revalidate=True,
         max_age=0)
     return response
示例#42
0
 def dispatch(self, *args, **kwargs):
     response = super(CachedTemplate, self).dispatch(*args, **kwargs)
     patch_cache_control(response, public=True, max_age=self.get_cache_timeout())
     return response
示例#43
0
文件: views.py 项目: jgasteiz/javiman
 def get(self, request, *args, **kwargs):
     response = super(CacheMixin, self).get(request, *args, **kwargs)
     patch_cache_control(response, public=True, max_age=MAX_AGE)
     response['Pragma'] = 'Public'
     return response
示例#44
0
文件: proxies.py 项目: ngageoint/geoq
            if request.body != None and len(request.body) > 0:
                newrequest.add_data(request.body)

            proxied_request = urllib2.urlopen(newrequest, timeout=20)
            status_code = proxied_request.code
            mimetype = proxied_request.headers.typeheader or mimetypes.guess_type(url)
            content = proxied_request.read()
    except urllib2.HTTPError, e:
        status = {'status': 'error', 'details': 'Proxy HTTPError = ' + str(e.code)}
        errorCode = 'Proxy HTTPError = ' + str(e.code)
    except urllib2.URLError, e:
        status = {'status': 'error', 'details': 'Proxy URLError = ' + str(e.reason)}
        errorCode = 'Proxy URLError = ' + str(e.reason)
    except Exception:
        status = {'status': 'error', 'details': 'Proxy generic exception'}
        import traceback

        errorCode = 'Proxy generic exception: ' + traceback.format_exc()
    else:
        response = HttpResponse(content, status=status_code, mimetype=mimetype)

        if ".png" in url or ".jpg" in url:
            patch_cache_control(response, max_age=60 * 60 * 1, public=True) #Cache for 1 hour

        return response

    if errorCode and len(errorCode):
        logger.error(errorCode)
    output = json.dumps(status)
    return HttpResponse(output, content_type="application/json")
示例#45
0
    def wrapper(*args, **kwargs):
        response = function(*args, **kwargs)

        patch_cache_control(response, no_cache=True, no_store=True,
                            must_revalidate=True, max_age=0)
        return response