Beispiel #1
0
 def done(self, form_list, **kwargs):
     combined = {}
     for form in form_list:
         combined.update(form.cleaned_data)
     contact = models.Contact(**combined)
     contact.search = self.search
     contact.save()
     by_agency = {}
     for opp in self.opportunities:
         contact.opportunities.add(opp)
         agency = opp.agency
         by_agency.setdefault(agency, []).append(opp)
     set_script_prefix(settings.SITE_URL)
     for agency, opps in by_agency.items():
         tmp = loader.get_template('primerpeso/email.txt')
         body = tmp.render(Context({
             'contact': contact,
             'search': self.search,
             'agency': agency,
             'opportunities': opps,
         }))
         email = EmailMessage(
             _('Application Form PrimerPeso'),
             body,
             '*****@*****.**',
             [agency.email, contact.email],
             [],
             reply_to=[agency.email, contact.email],
         )
         email.send()
     set_script_prefix('')
     url = reverse('thanks')
     return redirect(url)
Beispiel #2
0
 def process_request(self, request):
     schema = 'http://'
     if request.is_secure():
         schema = 'https://'
     host = request.get_host()
     if host:
         set_script_prefix('%s%s' % (schema, host))
Beispiel #3
0
    def get(self, *args, **kwargs):
        # type: (*Any, **Any) -> None
        environ = WSGIContainer.environ(self.request)
        environ['PATH_INFO'] = urllib.parse.unquote(environ['PATH_INFO'])
        request = WSGIRequest(environ)
        request._tornado_handler = self

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            response = self.get_response(request)

            if not response:
                return
        finally:
            signals.request_finished.send(sender=self.__class__)

        self.set_status(response.status_code)
        for h in response.items():
            self.set_header(h[0], h[1])

        if not hasattr(self, "_new_cookies"):
            self._new_cookies = []  # type: List[http.cookie.SimpleCookie]
        self._new_cookies.append(response.cookies)

        self.write(response.content)
        self.finish()
Beispiel #4
0
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            request = self.request_class(environ)
        except UnicodeDecodeError:
            logger.warning("Bad Request (UnicodeDecodeError)", exc_info=sys.exc_info(), extra={"status_code": 400})
            response = http.HttpResponseBadRequest()
        else:
            response = self.get_response(request)

        response._handler_class = self.__class__

        status = "%s %s" % (response.status_code, response.reason_phrase)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append((str("Set-Cookie"), str(c.output(header=""))))
        start_response(force_str(status), response_headers)
        return response
 def test_get_absolute_url_honors_script_prefix(self):
     pf = FlatPage(title="Tea!", url="/tea/")
     set_script_prefix("/beverages/")
     try:
         self.assertEqual(pf.get_absolute_url(), "/beverages/tea/")
     finally:
         clear_script_prefix()
        def __call__(self, environ, start_response):
            if self._request_middleware is None:
                with self.initLock:
                    try:
                        if self._request_middleware is None:
                            self.load_middleware()
                    except:
                        self._request_middleware = None
                        raise

            set_script_prefix(base.get_script_name(environ))
            signals.request_started.send(sender=self.__class__)
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                log.warning('Bad Request (UnicodeDecodeError)', exc_info=sys.exc_info(), extra={'status_code': 400, })
                response = http.HttpResponseBadRequest()
            else:
                response = yield self.get_response(request)

            response._handler_class = self.__class__

            try:
                status_text = STATUS_CODE_TEXT[response.status_code]
            except KeyError:
                status_text = 'UNKNOWN STATUS CODE'
            status = '%s %s' % (response.status_code, status_text)
            response_headers = [(str(k), str(v)) for k, v in response.items()]
            for c in response.cookies.values():
                response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
            start_response(force_str(status), response_headers)
            yield response
Beispiel #7
0
 def __call__(self, message):
     # Set script prefix from message root_path
     set_script_prefix(message.get("root_path", ""))
     signals.request_started.send(sender=self.__class__, message=message)
     # Run request through view system
     try:
         request = self.request_class(message)
     except UnicodeDecodeError:
         logger.warning("Bad Request (UnicodeDecodeError)", exc_info=sys.exc_info(), extra={"status_code": 400})
         response = http.HttpResponseBadRequest()
     except RequestTimeout:
         # Parsing the rquest failed, so the response is a Request Timeout error
         response = HttpResponse("408 Request Timeout (upload too slow)", status_code=408)
     except RequestAborted:
         # Client closed connection on us mid request. Abort!
         return
     else:
         try:
             response = self.get_response(request)
             # Fix chunk size on file responses
             if isinstance(response, FileResponse):
                 response.block_size = 1024 * 512
         except AsgiRequest.ResponseLater:
             # The view has promised something else
             # will send a response at a later time
             return
     # Transform response into messages, which we yield back to caller
     for message in self.encode_response(response):
         # TODO: file_to_stream
         yield message
     # Close the response now we're done with it
     response.close()
Beispiel #8
0
    def handle(self, *args, **options):
        # commands need explicit activation of translations
        translation.activate(settings.LANGUAGE_CODE)
        # this causes url handling to force absolute urls
        url = "https://%s/" % Site.objects.get_current().domain
        set_script_prefix(url)

        try:
            if args:
                now = datetime.datetime.strptime(args[0], '%d.%m.%Y')
            else:
                # yesterday
                now = datetime.date.today() - datetime.timedelta(1)

            subject = 'Kiberpipa, weekly report: %d. %d. %d' % (now.day, now.month, now.year)
            days_range = 7
            events = Event.objects.all()

            # 1. events that are newer or equal may pass
            # 2. events that are older or equal may pass
            events = events.filter(start_date__gte=(now - datetime.timedelta(days=days_range))).filter(start_date__lte=now)

            all_visitors = 0
            for e in events:
                all_visitors += e.visitors

            # is public and no visitors
            no_visitors = events.filter(public__exact=True).filter(visitors__exact=0)

            # is videoed and no attached video
            no_video = events.filter(require_video__exact=True).filter(video__isnull=True)

            # is pictured and no flicker id
            no_pictures = events.filter(require_photo__exact=True).filter(flickr_set_id__exact=None)

            if events.count() == 0:
                print "no events to send"
                return

            unfinished_events = (no_visitors, no_video, no_pictures)
            html = get_template('mail/events_report.html').render(Context({
                                                                  'days_range': days_range,
                                                                  'all_visitors': all_visitors,
                                                                  'events': events,
                                                                  'unfinished_events': unfinished_events
                                                                  }))
            text = get_template('mail/events_report.txt').render(Context({
                                                                  'days_range': days_range,
                                                                  'all_visitors': all_visitors,
                                                                  'events': events,
                                                                  'unfinished_events': unfinished_events
                                                                  }))

            email = EmailMultiAlternatives(subject, text, settings.DEFAULT_FROM_EMAIL, ['*****@*****.**'])
            email.attach_alternative(html, 'text/html')
            email.send()
            print "events email sent"
        finally:
            # set_script_prefix is global for current thread
            clear_script_prefix()
Beispiel #9
0
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            with self.initLock:
                # Check that middleware is still uninitialized.
                if self._request_middleware is None:
                    self.load_middleware()

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__, environ=environ)
        try:
            request = self.request_class(environ)
        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 400,
                }
            )
            response = http.HttpResponseBadRequest()
        else:
            response = self.get_response(request)

        response._handler_class = self.__class__

        status = '%s %s' % (response.status_code, response.reason_phrase)
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
        start_response(force_str(status), response_headers)
        if getattr(response, 'file_to_stream', None) is not None and environ.get('wsgi.file_wrapper'):
            response = environ['wsgi.file_wrapper'](response.file_to_stream)
        return response
Beispiel #10
0
    def get(self):
        from tornado.wsgi import WSGIContainer
        from django.core.handlers.wsgi import WSGIRequest, get_script_name
        import urllib

        environ  = WSGIContainer.environ(self.request)
        environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO'])
        request  = WSGIRequest(environ)
        request._tornado_handler     = self

        set_script_prefix(get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            response = self.get_response(request)

            if not response:
                return
        finally:
            signals.request_finished.send(sender=self.__class__)

        self.set_status(response.status_code)
        for h in response.items():
            self.set_header(h[0], h[1])

        if not hasattr(self, "_new_cookies"):
            self._new_cookies = []
        self._new_cookies.append(response.cookies)

        self.write(response.content)
        self.finish()
Beispiel #11
0
 def __call__(self, message):
     # Set up middleware if needed. We couldn't do this earlier, because
     # settings weren't available.
     if self._request_middleware is None:
         with self.initLock:
             # Check that middleware is still uninitialized.
             if self._request_middleware is None:
                 self.load_middleware()
     # Set script prefix from message root_path
     set_script_prefix(message.get('root_path', ''))
     signals.request_started.send(sender=self.__class__, message=message)
     # Run request through view system
     try:
         request = self.request_class(message)
     except UnicodeDecodeError:
         logger.warning(
             'Bad Request (UnicodeDecodeError)',
             exc_info=sys.exc_info(),
             extra={
                 'status_code': 400,
             }
         )
         response = http.HttpResponseBadRequest()
     else:
         try:
             response = self.get_response(request)
         except AsgiRequest.ResponseLater:
             # The view has promised something else
             # will send a response at a later time
             return
     # Transform response into messages, which we yield back to caller
     for message in self.encode_response(response):
         # TODO: file_to_stream
         yield message
Beispiel #12
0
    def __call__(self, environ, start_response):
        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.

        # 这里的检测: 因为 self._request_middleware 是最后才设定的, 所以如果为空,
        # 很可能是因为 self.load_middleware() 没有调用成功.
        if self._request_middleware is None:
            with self.initLock:
                try:
                    # Check that middleware is still uninitialised.
                    if self._request_middleware is None:
                        因为 load_middleware() 可能没有调用, 调用一次.
                        self.load_middleware()
                except:
                    # Unload whatever middleware we got
                    self._request_middleware = None
                    raise

        set_script_prefix(base.get_script_name(environ))
        signls.request_started.send(sender=self.__class__) # __class__ 代表自己的类

        try:
            # 实例化 request_class = WSGIRequest, 将在日后文章中展开, 可以将其视为一个代表 http 请求的类
            request = self.request_class(environ)

        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                exc_info=sys.exc_info(),
                extra={
                    'status_code': 400,
                }
            )
            response = http.HttpResponseBadRequest()
        else:
            # 调用 self.get_response(), 将会返回一个相应对象 response
            response = self.get_response(request)

        # 将 self 挂钩到 response 对象
        response._handler_class = self.__class__

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'

         # 状态码
        status = '%s %s' % (response.status_code, status_text)

        response_headers = [(str(k), str(v)) for k, v in response.items()]

        # 对于每个一个 cookie, 都在 header 中设置: Set-cookie xxx=yyy
        for c in response.cookies.values():
            response_headers.append((str('Set-Cookie'), str(c.output(header=''))))

        # start_response() 操作已经在上节中介绍了
        start_response(force_str(status), response_headers)

        # 成功返回相应对象
        return response
def app_reverse(viewname, urlconf=None, args=None, kwargs=None,
                *vargs, **vkwargs):
    """
    Reverse URLs from application contents
    Works almost like Django's own reverse() method except that it resolves
    URLs from application contents. The second argument, ``urlconf``, has to
    correspond to the URLconf parameter passed in the ``APPLICATIONS`` list
    to ``Page.create_content_type``::
        app_reverse('mymodel-detail', 'myapp.urls', args=...)
        or
        app_reverse('mymodel-detail', 'myapp.urls', kwargs=...)
    The second argument may also be a request object if you want to reverse
    an URL belonging to the current application content.
    """

    # First parameter might be a request instead of an urlconf path, so
    # we'll try to be helpful and extract the current urlconf from it
    extra_context = getattr(urlconf, '_feincms_extra_context', {})
    appconfig = extra_context.get('app_config', {})
    urlconf = appconfig.get('urlconf_path', urlconf)
    appcontent_class = ApplicationWidget._feincms_content_models[0]
    cache_key = appcontent_class.app_reverse_cache_key(urlconf)
    url_prefix = cache.get(cache_key)

    if url_prefix is None:

        clear_script_prefix()

        content = appcontent_class.closest_match(urlconf)

        if content is not None:
            if urlconf in appcontent_class.ALL_APPS_CONFIG:
                # We have an overridden URLconf
                app_config = appcontent_class.ALL_APPS_CONFIG[urlconf]
                urlconf = app_config['config'].get('urls', urlconf)

            prefix = content.parent.get_absolute_url()
            prefix += '/' if prefix[-1] != '/' else ''

            url_prefix = (urlconf, prefix)

            cache.set(cache_key, url_prefix, timeout=APP_REVERSE_CACHE_TIMEOUT)

    if url_prefix:
        # vargs and vkwargs are used to send through additional parameters
        # which are uninteresting to us (such as current_app)
        prefix = get_script_prefix()
        try:
            set_script_prefix(url_prefix[1])
            return reverse(
                viewname,
                url_prefix[0],
                args=args,
                kwargs=kwargs,
                *vargs, **vkwargs)
        finally:
            set_script_prefix(prefix)

    raise NoReverseMatch("Unable to find ApplicationContent for %r" % urlconf)
 def test_prefixes(self):
     prefixes = ["/gibbarish/", "/c/", "", "/X/"]
     for prefix in prefixes:
         set_script_prefix(prefix)
         out = Template(
             "{% load noprefix_url %}" "Chicken sandwich: {% noprefix_url 'day-view' '2015' '01' '01' %}"
         ).render(Context())
         self.assertEqual(out, "Chicken sandwich: /programme/view/2015/01/01")
Beispiel #15
0
def refresh_stats(**options):
    # The script prefix needs to be set here because the generated
    # URLs need to be aware of that and they are cached. Ideally
    # Django should take care of setting this up, but it doesn't yet:
    # https://code.djangoproject.com/ticket/16734
    script_name = u"/" if settings.FORCE_SCRIPT_NAME is None else force_unicode(settings.FORCE_SCRIPT_NAME)
    set_script_prefix(script_name)
    super(Command, Command()).handle_noargs(**options)
Beispiel #16
0
 def process_request(self, request):
     base_path = request.path.split('/')[1]
     request.brand = "democracyclub"
     if base_path in settings.EMBED_PREFIXES:
         request.brand = base_path
         set_script_prefix("/%s" % base_path)
     if base_path in settings.WHITELABEL_PREFIXES:
         request.brand = base_path
Beispiel #17
0
def update_cache(instance, keys):
    """RQ job"""
    # The script prefix needs to be set here because the generated
    # URLs need to be aware of that and they are cached. Ideally
    # Django should take care of setting this up, but it doesn't yet:
    # https://code.djangoproject.com/ticket/16734
    script_name = (u'/' if settings.FORCE_SCRIPT_NAME is None
                        else force_unicode(settings.FORCE_SCRIPT_NAME))
    set_script_prefix(script_name)
    instance._update_cache(keys)
    def test_script_name(self):
        rf = RequestFactory()
        request = rf.get("/foo", SCRIPT_NAME="/oremj")
        prefixer = urlresolvers.Prefixer(request)
        eq_(prefixer.fix(prefixer.shortened_path), "/oremj/en-US/firefox/foo")

        # Now check reverse.
        urlresolvers.set_url_prefix(prefixer)
        set_script_prefix("/oremj")
        eq_(urlresolvers.reverse("home"), "/oremj/en-US/firefox/")
Beispiel #19
0
    def test_force_script_name(self):
        from django.core.urlresolvers import set_script_prefix, _prefixes

        try:
            set_script_prefix("/force_script")
            self.result = self.get_result()  # To take override_settings in account
        finally:
            del _prefixes.value

        self.assertEqual(self.result['django_js_urls'], '/force_script/djangojs/urls')
Beispiel #20
0
    def test_script_name(self):
        rf = RequestFactory()
        request = rf.get('/foo', SCRIPT_NAME='/oremj')
        prefixer = urlresolvers.Prefixer(request)
        eq_(prefixer.fix(prefixer.shortened_path), '/oremj/en-US/firefox/foo')

        # Now check reverse.
        urlresolvers.set_url_prefix(prefixer)
        set_script_prefix('/oremj')
        eq_(urlresolvers.reverse('home'), '/oremj/en-US/firefox/')
Beispiel #21
0
    def test_force_script_name(self):
        from django.core.urlresolvers import set_script_prefix, _prefixes
        try:
            url = reverse('django_js_urls')
            set_script_prefix("/force_script")
            response = self.client.get(url)
        finally:
            del _prefixes.value

        result = json.loads(response.content.decode())
        self.assertEqual(result['django_js_urls'], '/force_script/djangojs/urls')
Beispiel #22
0
    def __call__(self, req):
        warn(('The mod_python handler is deprecated; use a WSGI or FastCGI server instead.'),
             PendingDeprecationWarning)

        # mod_python fakes the environ, and thus doesn't process SetEnv.  This fixes that
        os.environ.update(req.subprocess_env)

        # now that the environ works we can see the correct settings, so imports
        # that use settings now can work
        from django.conf import settings

        # if we need to set up middleware, now that settings works we can do it now.
        if self._request_middleware is None:
            self.load_middleware()

        set_script_prefix(req.get_options().get('django.root', ''))
        signals.request_started.send(sender=self.__class__)
        try:
            try:
                request = self.request_class(req)
            except UnicodeDecodeError:
                logger.warning('Bad Request (UnicodeDecodeError): %s' % request.path,
                    exc_info=sys.exc_info(),
                    extra={
                        'status_code': 400,
                        'request': request
                    }
                )
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)

                # Apply response middleware
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        # Convert our custom HttpResponse object back into the mod_python req.
        req.content_type = response['Content-Type']
        for key, value in response.items():
            if key != 'content-type':
                req.headers_out[str(key)] = str(value)
        for c in response.cookies.values():
            req.headers_out.add('Set-Cookie', c.output(header=''))
        req.status = response.status_code
        try:
            for chunk in response:
                req.write(chunk)
        finally:
            response.close()

        return 0 # mod_python.apache.OK
 def initial(self, request, *args, **kargs):
     """
     Hook for any code that needs to run prior to anything else.
     Required if you want to do things like set `request.upload_handlers` before
     the authentication and dispatch handling is run.
     """
     # Calls to 'reverse' will not be fully qualified unless we set the
     # scheme/host/port here.
     self.orig_prefix = get_script_prefix()
     if not (self.orig_prefix.startswith('http:') or self.orig_prefix.startswith('https:')):
         prefix = '%s://%s' % (request.is_secure() and 'https' or 'http', request.get_host())
         set_script_prefix(prefix + self.orig_prefix)
Beispiel #24
0
    def handle_noargs(self, **options):
        # The script prefix needs to be set here because the generated
        # URLs need to be aware of that and they are cached. Ideally
        # Django should take care of setting this up, but it doesn't yet:
        # https://code.djangoproject.com/ticket/16734
        script_name = (u'/' if settings.FORCE_SCRIPT_NAME is None
                            else force_unicode(settings.FORCE_SCRIPT_NAME))
        set_script_prefix(script_name)

        failed_queue = get_failed_queue()
        for job_id in failed_queue.get_job_ids():
            failed_queue.requeue(job_id=job_id)
Beispiel #25
0
    def __call__(self, t_req, on_finish=None):
        """todo: Docstring for __call__

        :param t_req: A tornado HTTPServerRequest instnace
        :type t_req: tornado HTTPServerRequest instnace
        :return:
        :rtype:
        """
        logger.debug("TornadoHandler __call__()")
        # logger.debug("TornadoHandler __call__ %s", t_req)
        self._when_finished = on_finish
        self.tornado_request = t_req
        self.tornado_future = None

        self.urlconf = settings.ROOT_URLCONF
        self.resolver = urlresolvers.RegexURLResolver(r'^/', self.urlconf)
        self.callback, self.callback_args, self.callback_kwargs = (None, None, None)

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            # with self.initLock:
            try:
                # Check that middleware is still uninitialized.
                if self._request_middleware is None:
                    self.load_middleware()
            except:
                # Unload whatever middleware we got
                self._request_middleware = None
                raise

        set_script_prefix(get_script_name(t_req))

        signals.request_started.send(sender=self.__class__)
        try:
            request = self.request_class(t_req, self)
        except UnicodeDecodeError:
            logger.warning('Bad Request (UnicodeDecodeError)',
                           exc_info=sys.exc_info(),
                           extra={
                               'status_code': 400,
                           }
                           )
            response = http.HttpResponseBadRequest()
        else:
            # Send this DjangoRequest through the Django stack
            logger.debug("process request")
            response = self.get_response(request)

        # logger.debug("Done, returning response, _response_finished: %s", self._response_finished)
        if not self._response_finished:
            return response
Beispiel #26
0
 def handle(self, *args, **options):
     script_prefix = settings.PETRIFY_EXPORT_URL
     old_static_url = settings.STATIC_URL
     try:
         settings.STATIC_URL = script_prefix[:-1] + settings.STATIC_URL
         set_script_prefix(script_prefix)
         client = Client()
         for url in get_pages_urls():
             export_url(client, url[len(script_prefix) - 1 :])
         for url in get_entities_urls():
             export_url(client, url[len(script_prefix) - 1 :])
     finally:
         settings.STATIC_URL = old_static_url
Beispiel #27
0
    def __call__(self, environ, start_response):
        from django.conf import settings

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        if self._request_middleware is None:
            self.initLock.acquire()
            # Check that middleware is still uninitialised.
            if self._request_middleware is None:
                self.load_middleware()
            self.initLock.release()

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            try:
                request = self.request_class(environ)
            except UnicodeDecodeError:
                response = http.HttpResponseBadRequest()
            else:
                response = self.get_response(request)

                # Apply response middleware
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)

        if hasattr(response, 'sendfile_filename') and response.has_header('Content-Length'):
            del response['Content-Length']
        response_headers = [(str(k), str(v)) for k, v in response.items()]
        for c in response.cookies.values():
            response_headers.append(('Set-Cookie', str(c.output(header=''))))
        start_response(status, response_headers)
        if hasattr(response, 'sendfile_filename'):
            filelike = open(response.sendfile_filename, 'rb')
            block_size = response.block_size
            if 'wsgi.file_wrapper' in environ:
                return environ['wsgi.file_wrapper'](filelike, block_size)
            else:
                return iter(lambda: filelike.read(block_size), '')

        return response
Beispiel #28
0
    def test_chlocale_filter_no_default_prefix(self):
        self.settings_manager.set(PREFIX_DEFAULT_LOCALE=False)
        reload(localeurl_settings)

        for script_name in ["", "/mountpoint", "/mountpoint/"]:
            
            urlresolvers.set_script_prefix(script_name)
            script_name = script_name.rstrip("/")
                
            self.assertEqual(script_name+'/dummy/', self.render_template(
                    '{{ "%s/nl-nl/dummy/"|chlocale:"en-gb" }}'%script_name))
    
            self.assertEqual(script_name+'/fr/dummy/', self.render_template(
                    '{{"%s/nl-nl/dummy/"|chlocale:"fr"}}'%script_name))
Beispiel #29
0
    def test_locale_url_tag_no_default_prefix(self):
        self.settings_manager.set(PREFIX_DEFAULT_LOCALE=False)
        reload(localeurl_settings)

        for script_name in ["", "/mountpoint", "/mountpoint/"]:
            
            urlresolvers.set_script_prefix(script_name)
            script_name = script_name.rstrip("/")
                
            self.assertEqual(script_name+'/dummy/', self.render_template(
                    '{% locale_url "en-us" dummy0 %}'))
    
            self.assertEqual(script_name+'/fr/dummy/', self.render_template(
                '{% locale_url "fr" dummy0 %}'))
Beispiel #30
0
def update_cache_job(instance):
    """RQ job"""
    # The script prefix needs to be set here because the generated
    # URLs need to be aware of that and they are cached. Ideally
    # Django should take care of setting this up, but it doesn't yet:
    # https://code.djangoproject.com/ticket/16734
    script_name = (u'/' if settings.FORCE_SCRIPT_NAME is None
                        else force_unicode(settings.FORCE_SCRIPT_NAME))
    set_script_prefix(script_name)
    job = get_current_job()
    job_wrapper = JobWrapper(job.id, job.connection)
    keys, decrement = job_wrapper.get_job_params()
    instance._update_cache_job(keys, decrement)
    job_wrapper.clear_job_params()
Beispiel #31
0
def app_reverse(viewname, urlconf=None, args=None, kwargs=None,
                *vargs, **vkwargs):
    """
    Reverse URLs from application contents

    Works almost like Django's own reverse() method except that it resolves
    URLs from application contents. The second argument, ``urlconf``, has to
    correspond to the URLconf parameter passed in the ``APPLICATIONS`` list
    to ``Page.create_content_type``::

        app_reverse('mymodel-detail', 'myapp.urls', args=...)

        or

        app_reverse('mymodel-detail', 'myapp.urls', kwargs=...)

    The second argument may also be a request object if you want to reverse
    an URL belonging to the current application content.
    """

    # First parameter might be a request instead of an urlconf path, so
    # we'll try to be helpful and extract the current urlconf from it
    extra_context = getattr(urlconf, '_feincms_extra_context', {})
    appconfig = extra_context.get('app_config', {})
    urlconf = appconfig.get('urlconf_path', urlconf)

    appcontent_class = ApplicationContent._feincms_content_models[0]
    cache_key = appcontent_class.app_reverse_cache_key(urlconf)
    url_prefix = cache.get(cache_key)

    if url_prefix is None:
        content = appcontent_class.closest_match(urlconf)

        if content is not None:
            if urlconf in appcontent_class.ALL_APPS_CONFIG:
                # We have an overridden URLconf
                app_config = appcontent_class.ALL_APPS_CONFIG[urlconf]
                urlconf = app_config['config'].get('urls', urlconf)

            prefix = content.parent.get_absolute_url()
            prefix += '/' if prefix[-1] != '/' else ''

            url_prefix = (urlconf, prefix)
            cache.set(cache_key, url_prefix, timeout=APP_REVERSE_CACHE_TIMEOUT)

    if url_prefix:
        # vargs and vkwargs are used to send through additional parameters
        # which are uninteresting to us (such as current_app)
        prefix = get_script_prefix()
        try:
            set_script_prefix(url_prefix[1])
            return reverse(
                viewname,
                url_prefix[0],
                args=args,
                kwargs=kwargs,
                *vargs, **vkwargs)
        finally:
            set_script_prefix(prefix)

    raise NoReverseMatch("Unable to find ApplicationContent for %r" % urlconf)
Beispiel #32
0
class View(ResourceMixin, RequestMixin, ResponseMixin, AuthMixin, DjangoView):
    """
    Handles incoming requests and maps them to REST operations.
    Performs request deserialization, response serialization, authentication and input validation.
    """
    """
    The resource to use when validating requests and filtering responses,
    or `None` to use default behaviour.
    """
    resource = None
    """
    List of renderers the resource can serialize the response with, ordered by preference.
    """
    renderers = renderers.DEFAULT_RENDERERS
    """
    List of parsers the resource can parse the request with.
    """
    parsers = parsers.DEFAULT_PARSERS
    """
    List of all authenticating methods to attempt.
    """
    authentication = (authentication.UserLoggedInAuthentication,
                      authentication.BasicAuthentication)
    """
    List of all permissions that must be checked.
    """
    permissions = (permissions.FullAnonAccess, )

    @classmethod
    def as_view(cls, **initkwargs):
        """
        Override the default :meth:`as_view` to store an instance of the view
        as an attribute on the callable function.  This allows us to discover
        information about the view when we do URL reverse lookups.
        """
        view = super(View, cls).as_view(**initkwargs)
        view.cls_instance = cls(**initkwargs)
        return view

    @property
    def allowed_methods(self):
        """
        Return the list of allowed HTTP methods, uppercased.
        """
        return [
            method.upper() for method in self.http_method_names
            if hasattr(self, method)
        ]

    def http_method_not_allowed(self, request, *args, **kwargs):
        """
        Return an HTTP 405 error if an operation is called which does not have a handler method.
        """
        raise ErrorResponse(status.HTTP_405_METHOD_NOT_ALLOWED, {
            'detail':
            'Method \'%s\' not allowed on this resource.' % self.method
        })

    def initial(self, request, *args, **kargs):
        """
        Hook for any code that needs to run prior to anything else.
        Required if you want to do things like set `request.upload_handlers` before
        the authentication and dispatch handling is run.
        """
        pass

    def add_header(self, field, value):
        """
        Add *field* and *value* to the :attr:`headers` attribute of the :class:`View` class.
        """
        self.headers[field] = value

    # Note: session based authentication is explicitly CSRF validated,
    # all other authentication is CSRF exempt.
    @csrf_exempt
    def dispatch(self, request, *args, **kwargs):
        self.request = request
        self.args = args
        self.kwargs = kwargs
        self.headers = {}

        # Calls to 'reverse' will not be fully qualified unless we set the scheme/host/port here.
        orig_prefix = get_script_prefix()
        prefix = '%s://%s' % (request.is_secure() and 'https'
                              or 'http', request.get_host())
        set_script_prefix(prefix + orig_prefix)

        try:
            self.initial(request, *args, **kwargs)

            # Authenticate and check request has the relevant permissions
            self._check_permissions()

            # Get the appropriate handler method
            if self.method.lower() in self.http_method_names:
                handler = getattr(self, self.method.lower(),
                                  self.http_method_not_allowed)
            else:
                handler = self.http_method_not_allowed

            response_obj = handler(request, *args, **kwargs)

            # Allow return value to be either HttpResponse, Response, or an object, or None
            if isinstance(response_obj, HttpResponse):
                return response_obj
            elif isinstance(response_obj, Response):
                response = response_obj
            elif response_obj is not None:
                response = Response(status.HTTP_200_OK, response_obj)
            else:
                response = Response(status.HTTP_204_NO_CONTENT)

            if request.method == 'OPTIONS':
                # do not filter the response for HTTP OPTIONS, else the response fields are lost,
                # as they do not correspond with model fields
                response.cleaned_content = response.raw_content
            else:
                # Pre-serialize filtering (eg filter complex objects into natively serializable types)
                response.cleaned_content = self.filter_response(
                    response.raw_content)

        except ErrorResponse, exc:
            response = exc.response

        # Always add these headers.
        #
        # TODO - this isn't actually the correct way to set the vary header,
        # also it's currently sub-optimal for HTTP caching - need to sort that out.
        response.headers['Allow'] = ', '.join(self.allowed_methods)
        response.headers['Vary'] = 'Authenticate, Accept'

        # merge with headers possibly set at some point in the view
        response.headers.update(self.headers)

        set_script_prefix(orig_prefix)

        return self.render(response)
Beispiel #33
0
 def tearDown(self):
     urlresolvers.clean_url_prefixes()
     set_script_prefix('/')
     super(TestPrefixer, self).tearDown()
Beispiel #34
0
 def __enter__(self):
     set_script_prefix(self.prefix)
Beispiel #35
0
 def __exit__(self, exc_type, exc_val, traceback):
     set_script_prefix(self.old_prefix)
Beispiel #36
0
 def tearDown(self):
     urlresolvers.clean_url_prefixes()
     set_script_prefix('/')
Beispiel #37
0
 def enable(self):
     super(script_name, self).enable()
     set_script_prefix(self.newpath)
Beispiel #38
0
 def disable(self):
     super(script_name, self).disable()
     set_script_prefix(self.oldprefix)