Beispiel #1
0
 def process_response(self, request, response):
     __traceback_hide__ = True
     ident = thread.get_ident()
     toolbar = self.__class__.debug_toolbars.get(ident)
     if not toolbar:
         return response
     if isinstance(response, HttpResponseRedirect):
         if not toolbar.config['INTERCEPT_REDIRECTS']:
             return response
         redirect_to = response.get('Location', None)
         if redirect_to:
             cookies = response.cookies
             response = render_to_response('debug_toolbar/redirect.html',
                                           {'redirect_to': redirect_to})
             response.cookies = cookies
     if 'gzip' not in response.get('Content-Encoding', '') and \
        response.get('Content-Type', '').split(';')[0] in _HTML_TYPES:
         for panel in toolbar.panels:
             panel.process_response(request, response)
         if getattr(request, 'urlconf', None):
             set_urlconf(request.urlconf)
         response.content = replace_insensitive(
             smart_unicode(response.content), self.tag,
             smart_unicode(toolbar.render_toolbar() + self.tag))
         set_urlconf(None)
         if response.get('Content-Length', None):
             response['Content-Length'] = len(response.content)
     del self.__class__.debug_toolbars[ident]
     return response
Beispiel #2
0
def apply_view_middleware(request):
    """
    Apply all the `process_view` capable middleware configured
    into the given request.

    The logic is roughly copied from
    django.core.handlers.base.BaseHandler.get_response

    :param request: The request to massage.
    :type request: django.http.HttpRequest
    :return: The same request, massaged in-place.
    :rtype: django.http.HttpRequest
    """
    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    urlresolvers.set_urlconf(urlconf)
    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
    resolver_match = resolver.resolve(request.path_info)
    callback, callback_args, callback_kwargs = resolver_match
    request.resolver_match = resolver_match

    for middleware_path in settings.MIDDLEWARE_CLASSES:
        mw_class = import_string(middleware_path)
        try:
            mw_instance = mw_class()
        except MiddlewareNotUsed:
            continue

        if hasattr(mw_instance, 'process_view'):
            mw_instance.process_view(request, callback, callback_args, callback_kwargs)

    return request
Beispiel #3
0
    def request(self, **request_args):
        """Constructs a generic request object, INCLUDING middleware modifications."""

        from django.core import urlresolvers


        request = RequestFactory.request(self, **request_args)
        ###pprint.pprint(request)

        handler = BaseHandler()

        handler.load_middleware()

        for middleware_method in handler._request_middleware:
            #print("APPLYING REQUEST MIDDLEWARE ", middleware_method, file=sys.stderr)
            if middleware_method(request):
                raise Exception("Couldn't create request mock object - "
                                "request middleware returned a response")

        urlconf = settings.ROOT_URLCONF
        urlresolvers.set_urlconf(urlconf)
        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

        callback, callback_args, callback_kwargs = resolver.resolve(
                            request.path_info)

        # Apply view middleware
        for middleware_method in handler._view_middleware:
            #print("APPLYING VIEW MIDDLEWARE ", middleware_method, file=sys.stderr)
            response = middleware_method(request, callback, callback_args, callback_kwargs)
            if response:
                raise Exception("Couldn't create request mock object - "
                                "view middleware returned a response")

        return request
Beispiel #4
0
def reload_urlconf(urlconf=None):
    """Reload Synnefo's URLconf after ADMIN_BASE_URL is changed.

    This function should be called everytime ADMIN_BASE_URL is altered. It
    tries to propagate this change to the RegexURLResolver Django class by:
    a) Reloading the Admin settings and recalculating the BASE_PATH setting.
    b) Reloading the Admin urls, and thus recreating the Admin URLpatterns,
       which depend on the BASE_PATH setting.
    c) Reloading the Synnefo webproject URLs in order to integrate the new
       Admin URLs with the URLs of Synnefo.

    The cached Django RegexURLResolver has a pointer to the
    'synnefo.webproject.urls' module, so the changes should be instantly
    visible.

    The caller can optionally set a new URLconf to use.

    Before the end of the test, this function should always be called with no
    arguments once the ADMIN_BASE_URL is restored, in order to bring the test
    suite in its initial state.
    """
    reload(sys.modules['synnefo_admin.admin_settings'])
    reload(sys.modules['synnefo_admin.urls'])
    reload(sys.modules['synnefo.webproject.urls'])
    # Using this function with no urlconf will reset the ROOT_URLCONF to its
    # initial value.
    set_urlconf(urlconf)
Beispiel #5
0
def apply_view_middleware(request):
    """
    Apply all the `process_view` capable middleware configured
    into the given request.

    The logic is roughly copied from
    django.core.handlers.base.BaseHandler.get_response

    :param request: The request to massage.
    :type request: django.http.HttpRequest
    :return: The same request, massaged in-place.
    :rtype: django.http.HttpRequest
    """
    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    urlresolvers.set_urlconf(urlconf)
    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
    resolver_match = resolver.resolve(request.path_info)
    callback, callback_args, callback_kwargs = resolver_match
    request.resolver_match = resolver_match

    for middleware_path in settings.MIDDLEWARE_CLASSES:
        mw_class = import_string(middleware_path)
        try:
            mw_instance = mw_class()
        except MiddlewareNotUsed:
            continue

        if hasattr(mw_instance, 'process_view'):
            mw_instance.process_view(request, callback, callback_args, callback_kwargs)

    return request
Beispiel #6
0
    def __get__(self, request, obj_type=None):
        if not hasattr(request, '_cached_search'):
            Form = None
            request._cached_search = SearchData()

            # TODO constant to configure
            data = {
                # 'cl-ll': choices.ITEMS_PER_PAGE_CONST
            }

            # Get Admin instance
            urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
            urlresolvers.set_urlconf(urlconf)
            resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

            callback, callback_args, callback_kwargs = resolver.resolve(
                    request.path_info)
            admin = callback.func_closure[0].cell_contents

            if admin:
                Form = admin.filter_form
            else:
                Form = None

            if Form:
                data.update(dict(request.REQUEST))

                form = Form(data)
                form.is_valid()

                request._cached_search.filter_params = urlencode(form.cleaned_data_prefixed)
                request._cached_search.filter_form = form

        return request._cached_search
Beispiel #7
0
    def process_request(self, request):
        MULTISITE_CMS_URLS = getattr(settings, 'MULTISITE_CMS_URLS', {})
        MULTISITE_CMS_ALIASES = getattr(settings, 'MULTISITE_CMS_ALIASES', {})
        MULTISITE_CMS_FALLBACK = getattr(settings, 'MULTISITE_CMS_FALLBACK',
                                         '')
        try:
            parsed = urlparse.urlparse(request.build_absolute_uri())
            host = parsed.hostname.split(':')[0]
            urlconf = None
            try:
                urlconf = MULTISITE_CMS_URLS[host]
            except KeyError:
                for domain, hosts in MULTISITE_CMS_ALIASES.items():
                    if host in hosts and domain in MULTISITE_CMS_URLS:
                        urlconf = MULTISITE_CMS_URLS[domain]
                        break
            if (not urlconf and MULTISITE_CMS_FALLBACK
                    and MULTISITE_CMS_FALLBACK in MULTISITE_CMS_URLS.keys()):
                urlconf = MULTISITE_CMS_URLS[MULTISITE_CMS_FALLBACK]

            if urlconf:
                request.urlconf = urlconf
            # sets urlconf for current thread, so that code that does not know
            # about the request (e.g MyModel.get_absolute_url()) get the correct
            # urlconf.
            set_urlconf(urlconf)
            try:
                # In django CMS 3.4.2 this allows us to save a few queries thanks to per-site appresolvers caching
                reload_urlconf(clear_cache=False)
            except TypeError:
                reload_urlconf()
        except KeyError:
            # use default urlconf (settings.ROOT_URLCONF)
            set_urlconf(None)
 def process_response(self, request, response):
     __traceback_hide__ = True
     ident = thread.get_ident()
     toolbar = self.__class__.debug_toolbars.get(ident)
     if not toolbar:
         return response
     if isinstance(response, HttpResponseRedirect):
         if not toolbar.config['INTERCEPT_REDIRECTS']:
             return response
         redirect_to = response.get('Location', None)
         if redirect_to:
             cookies = response.cookies
             response = render_to_response(
                 'debug_toolbar/redirect.html',
                 {'redirect_to': redirect_to}
             )
             response.cookies = cookies
     if 'gzip' not in response.get('Content-Encoding', '') and \
        response.get('Content-Type', '').split(';')[0] in _HTML_TYPES:
         for panel in toolbar.panels:
             panel.process_response(request, response)
         if getattr(request, 'urlconf', None):
             set_urlconf(request.urlconf)
         response.content = replace_insensitive(
             smart_unicode(response.content),
             self.tag,
             smart_unicode(toolbar.render_toolbar() + self.tag))
         set_urlconf(None)
         if response.get('Content-Length', None):
             response['Content-Length'] = len(response.content)
     del self.__class__.debug_toolbars[ident]
     return response
Beispiel #9
0
    def process_request(self, request):
        # We try three options, in order of decreasing preference.
        if settings.USE_X_FORWARDED_HOST and ("HTTP_X_FORWARDED_HOST" in request.META):
            host = request.META["HTTP_X_FORWARDED_HOST"]
        elif "HTTP_HOST" in request.META:
            host = request.META["HTTP_HOST"]
        else:
            # Reconstruct the host using the algorithm from PEP 333.
            host = request.META["SERVER_NAME"]
            server_port = str(request.META["SERVER_PORT"])
            if server_port != ("443" if request.is_secure() else "80"):
                host = "%s:%s" % (host, server_port)

        domain, port = split_domain_port(host)
        default_domain, default_port = split_domain_port(urlparse(settings.SITE_URL).netloc)
        if domain:
            request.host = domain
            request.port = int(port) if port else None
            try:
                kd = KnownDomain.objects.get(domainname=domain)  # noqa
                request.domain = kd
            except:
                if settings.DEBUG or domain in LOCAL_HOST_NAMES or domain == default_domain:
                    request.urlconf = "pretix.multidomain.maindomain_urlconf"
                else:
                    raise DisallowedHost("Unknown host: %r" % host)
            else:
                request.organizer = kd.organizer
                request.urlconf = "pretix.multidomain.subdomain_urlconf"
        else:
            raise DisallowedHost("Invalid HTTP_HOST header: %r." % host)

        # We need to manually set the urlconf for the whole thread. Normally, Django's basic request
        # would do this for us, but we already need it in place for the other middlewares.
        set_urlconf(request.urlconf)
Beispiel #10
0
    def setUpClass(cls):
        cls.siteblocks = SiteBlocks()

        cls.b1 = Block(alias='main', url='*', contents='main_every_visible')
        cls.b1.save(force_insert=True)

        cls.b2 = Block(alias='main', description='hidden', url='*', contents='main_every_hidden', hidden=True)
        cls.b2.save(force_insert=True)

        cls.b3 = Block(alias='multiple', url='*', contents='multiple_1')
        cls.b3.save(force_insert=True)

        cls.b4 = Block(alias='multiple', url='*', contents='multiple_2')
        cls.b4.save(force_insert=True)

        cls.b5 = Block(alias='filtered_1', url='/news.*', contents='filtered_1_1')
        cls.b5.save(force_insert=True)

        cls.b6 = Block(alias='filtered_1', url='/gro{1,2}ves', contents='filtered_1_2')
        cls.b6.save(force_insert=True)

        cls.b7 = Block(alias='named_1', url=':named_url', contents='named_1_1')
        cls.b7.save(force_insert=True)

        cls.b8 = Block(alias='named_2', url=':namespaced:url', contents='named_2_1')
        cls.b8.save(force_insert=True)

        # set urlconf to one from test
        cls.old_urlconf = urlresolvers.get_urlconf()
        urlresolvers.set_urlconf('siteblocks.tests')
Beispiel #11
0
    def test_route_depth_url(self):
        urlconf = 'tests.urls'
        urlresolvers.set_urlconf(urlconf)
        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
        
        callback, args, kargs = resolver.resolve('/sample')
        request = MockRequest()
        self.assertEquals(sample.index(request, None), callback(request, *args, **kargs))

        callback, args, kargs = resolver.resolve('/sample/5')
        self.assertEquals(sample.show(request, '5'), callback(request, *args, **kargs))

        callback, args, kargs = resolver.resolve('/sample/5.xml')
        requestXML = MockRequest(app_name='djangobp.tests', format='xml')
        self.assertEquals(sample.show(requestXML, '5'), callback(request, *args, **kargs))

        callback, args, kargs = resolver.resolve('/sample/5.json')
        requestXML = MockRequest(app_name='djangobp.tests', format='json')
        self.assertEquals(sample.show(requestXML, '5'), callback(request, *args, **kargs))

        callback, args, kargs = resolver.resolve('/sample/ok/edit')
        self.assertEquals(sample.edit(request, 'ok'), callback(request, *args, **kargs))

        callback, args, kargs = resolver.resolve('/example/hello/test')
        self.assertEquals(example.test(request, 'hello'), callback(request, *args, **kargs))

        callback, args, kargs = resolver.resolve('/example/pick')
        self.assertEquals(example.pick(request, None), callback(request, *args, **kargs))

        callback, args, kargs = resolver.resolve('/example/nopick')
        self.assertEquals(example.show(request, 'nopick'), callback(request, *args, **kargs))
    def mock_hosts_middleware(self, request):
        # This is certainly rather annoying, but needed because
        # we have to reload everything as we're changing settings
        # dynamically.
        import django_hosts
        reload(django_hosts)
        import main.hosts
        reload(main.hosts)
        import django_hosts.reverse
        reload(django_hosts.reverse)
        import django_hosts.middleware
        reload(django_hosts.middleware)
        from django_hosts.middleware import BaseHostsMiddleware

        current_urlconf = get_urlconf() or settings.ROOT_URLCONF
        middleware = BaseHostsMiddleware()
        host, kwargs = middleware.get_host(request.get_host())
        request.urlconf = host.urlconf
        request.host = host
        set_urlconf(host.urlconf)

        # Annddd we also need to render the phased template response, too! Whew.
        

        yield

        set_urlconf(current_urlconf)
Beispiel #13
0
def reload_urlconf(urlconf=None):
    """Reload Synnefo's URLconf after ADMIN_BASE_URL is changed.

    This function should be called everytime ADMIN_BASE_URL is altered. It
    tries to propagate this change to the RegexURLResolver Django class by:
    a) Reloading the Admin settings and recalculating the BASE_PATH setting.
    b) Reloading the Admin urls, and thus recreating the Admin URLpatterns,
       which depend on the BASE_PATH setting.
    c) Reloading the Synnefo webproject URLs in order to integrate the new
       Admin URLs with the URLs of Synnefo.

    The cached Django RegexURLResolver has a pointer to the
    'synnefo.webproject.urls' module, so the changes should be instantly
    visible.

    The caller can optionally set a new URLconf to use.

    Before the end of the test, this function should always be called with no
    arguments once the ADMIN_BASE_URL is restored, in order to bring the test
    suite in its initial state.
    """
    reload(sys.modules['synnefo_admin.admin_settings'])
    reload(sys.modules['synnefo_admin.urls'])
    reload(sys.modules['synnefo.webproject.urls'])
    # Using this function with no urlconf will reset the ROOT_URLCONF to its
    # initial value.
    set_urlconf(urlconf)
Beispiel #14
0
def microsite_url(request, microsite_slug, url):
    microsite = get_object_or_404(MicroSite, slug=microsite_slug)
    perms_api.assert_has_permission(microsite, request.user, 'view')
    urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
    urlresolvers.set_urlconf(urlconf)
    index_prefix = request.get_full_path().index(microsite_slug)
    prefix = request.get_full_path()[:index_prefix + len(microsite_slug) + 1]
    resolver = urlresolvers.RegexURLResolver(r'^%s' % prefix, urlconf)
    newurl = request.path_info
    try:
        callback, callback_args, callback_kwargs = resolver.resolve(
                            newurl)
    except urlresolvers.Resolver404, e:
        if settings.APPEND_SLASH and (not newurl.endswith('/')):
            newurl = newurl + '/'
            if settings.DEBUG and request.method == 'POST':
                raise RuntimeError((""
                    "You called this URL via POST, but the URL doesn't end "
                    "in a slash and you have APPEND_SLASH set. Django can't "
                    "redirect to the slash URL while maintaining POST data. "
                    "Change your form to point to %s (note the trailing "
                    "slash), or set APPEND_SLASH=False in your Django "
                    "settings.") % newurl)
            return HttpResponseRedirect(newurl)
        raise e
Beispiel #15
0
def microsite_url(request, microsite_slug, url):
    microsite = get_object_or_404(MicroSite, slug=microsite_slug)
    perms_api.assert_has_permission(microsite, request.user, 'view')
    urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
    urlresolvers.set_urlconf(urlconf)
    index_prefix = request.get_full_path().index(microsite_slug)
    prefix = request.get_full_path()[:index_prefix + len(microsite_slug) + 1]
    resolver = urlresolvers.RegexURLResolver(r'^%s' % prefix, urlconf)
    newurl = request.path_info
    try:
        callback, callback_args, callback_kwargs = resolver.resolve(newurl)
    except urlresolvers.Resolver404, e:
        if settings.APPEND_SLASH and (not newurl.endswith('/')):
            newurl = newurl + '/'
            if settings.DEBUG and request.method == 'POST':
                raise RuntimeError(
                    (""
                     "You called this URL via POST, but the URL doesn't end "
                     "in a slash and you have APPEND_SLASH set. Django can't "
                     "redirect to the slash URL while maintaining POST data. "
                     "Change your form to point to %s (note the trailing "
                     "slash), or set APPEND_SLASH=False in your Django "
                     "settings.") % newurl)
            return HttpResponseRedirect(newurl)
        raise e
Beispiel #16
0
    def render(self, context):
        args = [arg.resolve(context) for arg in self.args]
        kwargs = dict([(smart_str(k, 'ascii'), v.resolve(context))
                       for k, v in self.kwargs.items()])

        view_name = self.view_name
        if not self.legacy_view_name:
            view_name = view_name.resolve(context)

        url = ''
        try:
            url = reverse(str(self.view_name), args=args, kwargs=kwargs, current_app=context.current_app)
        except NoReverseMatch, e:
            if settings.SETTINGS_MODULE:
                project_name = settings.SETTINGS_MODULE.split('.')[0]
                try:
                    url = reverse(project_name + '.' + str(self.view_name),
                                  args=args, kwargs=kwargs,
                                  current_app=context.current_app)
                except NoReverseMatch:
                    if self.view_name:
                        try:
                            urlresolvers.set_urlconf('eliar.urls')
                            url = reverse(str(self.view_name), args=args, kwargs=kwargs,
                                          current_app=context.current_app)
                        except NoReverseMatch, e:
                            try:
                                url = reverse(project_name + '.' + str(self.view_name), args=args, kwargs=kwargs,
                                              current_app=context.current_app)
                            except NoReverseMatch, e:
                                if self.asvar is None:
                                    raise e
                    else:
                        raise e
Beispiel #17
0
    def process_request(self, request):
        # We try three options, in order of decreasing preference.
        if settings.USE_X_FORWARDED_HOST and ('HTTP_X_FORWARDED_HOST' in request.META):
            host = request.META['HTTP_X_FORWARDED_HOST']
        elif 'HTTP_HOST' in request.META:
            host = request.META['HTTP_HOST']
        else:
            # Reconstruct the host using the algorithm from PEP 333.
            host = request.META['SERVER_NAME']
            server_port = str(request.META['SERVER_PORT'])
            if server_port != ('443' if request.is_secure() else '80'):
                host = '%s:%s' % (host, server_port)

        domain, port = split_domain_port(host)
        default_domain, default_port = split_domain_port(urlparse(settings.SITE_URL).netloc)
        if domain:
            request.host = domain
            request.port = int(port) if port else None
            try:
                kd = KnownDomain.objects.get(domainname=domain)  # noqa
                request.domain = kd
            except:
                if settings.DEBUG or domain in LOCAL_HOST_NAMES or domain == default_domain:
                    request.urlconf = "pretix.multidomain.maindomain_urlconf"
                else:
                    raise DisallowedHost("Unknown host: %r" % host)
            else:
                request.organizer = kd.organizer
                request.urlconf = "pretix.multidomain.subdomain_urlconf"
        else:
            raise DisallowedHost("Invalid HTTP_HOST header: %r." % host)

        # We need to manually set the urlconf for the whole thread. Normally, Django's basic request
        # would do this for us, but we already need it in place for the other middlewares.
        set_urlconf(request.urlconf)
Beispiel #18
0
    def __get__(self, request, obj_type=None):
        if not hasattr(request, "_cached_search"):
            Form = None
            request._cached_search = SearchData()

            # TODO constant to configure
            data = {
                # 'cl-ll': choices.ITEMS_PER_PAGE_CONST
            }

            # Get Admin instance
            urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
            urlresolvers.set_urlconf(urlconf)
            resolver = urlresolvers.RegexURLResolver(r"^/", urlconf)

            callback, callback_args, callback_kwargs = resolver.resolve(request.path_info)
            admin = callback.func_closure[0].cell_contents

            if admin:
                Form = admin.filter_form
            else:
                Form = None

            if Form:
                data.update(dict(request.REQUEST))

                form = Form(data)
                form.is_valid()

                request._cached_search.filter_params = urlencode(form.cleaned_data_prefixed)
                request._cached_search.filter_form = form

        return request._cached_search
    def process_request(self, request):
        if not getattr(_thread_local, "enabled", True):
            return

        host = request.get_host()

        # Find best match, falling back to settings.SUBDOMAIN_DEFAULT
        for subdomain in settings.SUBDOMAINS.values():
            match = subdomain["_regex"].match(host)
            if match:
                kwargs = match.groupdict()
                break
        else:
            kwargs = {}
            subdomain = self.default

        urlconf = subdomain["urlconf"]
        callback = subdomain["_callback"]

        request.urlconf = urlconf
        try:
            set_urlconf(urlconf)
            return callback(request, **kwargs)
        finally:
            set_urlconf(None)
Beispiel #20
0
 def process_response(self, request, response):
     """
     Ensures that
     404 raised from view functions are not caught by
     ``GenericTemplateFinderMiddleware``.
     """
     real_404 = getattr(request,
                        '_generic_template_finder_middleware_view_found',
                        False)
     if response.status_code == 404 and not real_404:
         try:
             if hasattr(request, 'urlconf'):
                 # Django calls response middlewares after it has unset the
                 # request's urlconf. Set it temporarily so the template can
                 # reverse properly.
                 urlresolvers.set_urlconf(request.urlconf)
             return generic_template_finder_view(
                 request, extra_context=self.get_extra_context(request))
         except Http404:
             return response
         except UnicodeEncodeError:
             return response
         finally:
             urlresolvers.set_urlconf(None)
     else:
         return response
Beispiel #21
0
    def process_request(self, request):
        if not getattr(_thread_local, 'enabled', True):
            return

        host = request.get_host()

        # Find best match, falling back to settings.SUBDOMAIN_DEFAULT
        for subdomain in settings.SUBDOMAINS.values():
            match = subdomain['_regex'].match(host)
            if match:
                kwargs = match.groupdict()
                break
        else:
            kwargs = {}
            subdomain = self.default

        urlconf = subdomain['urlconf']
        callback = subdomain['_callback']

        request.urlconf = urlconf
        try:
            set_urlconf(urlconf)
            return callback(request, **kwargs)
        finally:
            set_urlconf(None)
Beispiel #22
0
 def test_landing_advertiser(self):
     """ Assert build-your-network page loads correctly with referring ad rep
     advertiser in session (will have advertiser options).
     Urlconf specified in request to mimic action of initial page redirect
     to market (another test, tests the redirect functionality).
     """
     ad_rep = AD_REP_FACTORY.create_ad_rep()
     ad_rep.url = 'test_ad_rep_url'
     ad_rep.save()
     self.login(ad_rep.email)
     request = self.factory.get('/hudson-valley/build-your-network/')
     # Request factory isnt building urls with market, manually set urlconf:
     set_urlconf('urls_local.urls_2')
     request = self.add_session_to_request(request, ad_rep)
     Advertiser.objects.create_advertiser_from_consumer(
         ad_rep.consumer, advertiser_name='James', 
         advertiser_area_code='854', advertiser_exchange='555',
         advertiser_number='1688')
     response = show_ad_rep_menu(request, self.connector)
     self.assertEqual(response.status_code, 200)
     self.assertContains(response, 'Manage Coupons for')
     self.assertContains(response, 'Create Coupons for')
     self.assertContains(response, 'Another Local Business')
     self.assertContains(response, 'href="/hudson-valley/advertiser/"')
     set_urlconf('') # Reset urlconf used in these test cases.
Beispiel #23
0
    def process_response(self, request, response):
        try:
            if hasattr(response, 'render') and callable(response.render):
                return response.render()
            return response
        except Exception:
            import sys
            from django.conf import settings
            from django.core.handlers.base import BaseHandler
            from django.core import signals
            from django.core import urlresolvers

            urlconf = settings.ROOT_URLCONF
            urlresolvers.set_urlconf(urlconf)
            resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
            receivers = signals.got_request_exception.send(
                sender=self.__class__,
                request=request,
                )
            handler = BaseHandler()
            return handler.handle_uncaught_exception(
                request,
                resolver,
                sys.exc_info(),
                )
    def setUp(self):
        self.c = Client(SERVER_NAME="achetersanscom.dev", SERVER_PORT="8000")
        from sites.achetersanscom import urls

        set_urlconf(urls)
        from django.conf import settings

        settings.DEBUG = True
    def push(self, name, value):
        # save original value
        self._original_settings.setdefault(name, getattr(settings, name, NO_SETTING))

        if name == 'ROOT_URLCONF':
            set_urlconf(value)
        else:
            setattr(settings, name, value)
Beispiel #26
0
 def get_resolver(self, request):
     """
     Returns a django.core.urlresolvers.RegexURLResolver for the request's
     urlconf, falling back to the global urlconf fom settings.
     
     """
     urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
     urlresolvers.set_urlconf(urlconf)
     return urlresolvers.RegexURLResolver(r'^/', urlconf)
Beispiel #27
0
def get_proxy_resolver(urlconf, default_view):
    from django.conf import settings
    set_urlconf(urlconf)
    resolver = get_resolver(urlconf)
    callback = import_string(default_view)
    if callback not in resolver.reverse_dict:
        pattern = RegexURLPattern(r'', callback)
        resolver.url_patterns.append(pattern)
    return resolver
Beispiel #28
0
def get_proxy_resolver(urlconf, default_view):
  from django.conf import settings
  set_urlconf(urlconf)
  resolver = get_resolver(urlconf)
  callback = import_string(default_view)
  if callback not in resolver.reverse_dict:
    pattern = RegexURLPattern(r'', callback)
    resolver.url_patterns.append(pattern)
  return resolver
Beispiel #29
0
    def push(self, name, value):
        # save original value
        self._original_settings.setdefault(name,
                                           getattr(settings, name, NO_SETTING))

        if name == 'ROOT_URLCONF':
            set_urlconf(value)
        else:
            setattr(settings, name, value)
Beispiel #30
0
 def __getData(self, requestData):
     if '_links' in requestData:
         urlconf = settings.ROOT_URLCONF
         urlresolvers.set_urlconf(urlconf)
         resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
         for prop, url in requestData['_links'].items():
             requestData[prop] = self.__getObjectForUrl(url, resolver)
         del requestData['_links']
     return requestData
Beispiel #31
0
    def setUpClass(cls):
        cls.sitetree = SiteTree()

        t1 = Tree(alias='tree1')
        t1.save(force_insert=True)

        t1_root = TreeItem(title='root', tree=t1, url='/')
        t1_root.save(force_insert=True)

        t1_root_child1 = TreeItem(title='child1', tree=t1, parent=t1_root, url='/about/')
        t1_root_child1.save(force_insert=True)

        t1_root_child2 = TreeItem(title='child2', tree=t1, parent=t1_root, url='articles_list', urlaspattern=True)
        t1_root_child2.save(force_insert=True)

        t1_root_child2_sub1 = TreeItem(title='subchild1', tree=t1, parent=t1_root_child2,
            url='articles_detailed art_id', urlaspattern=True)
        t1_root_child2_sub1.save(force_insert=True)

        t1_root_child2_sub2 = TreeItem(title='subchild2', tree=t1, parent=t1_root_child2, url='/not_articles/10/')
        t1_root_child2_sub2.save(force_insert=True)

        t1_root_child3 = TreeItem(title='child_with_var_str', tree=t1, parent=t1_root, url='somevar_str', urlaspattern=True)
        t1_root_child3.save(force_insert=True)

        t1_root_child4 = TreeItem(title='child_with_var_list', tree=t1, parent=t1_root, url='somevar_list', urlaspattern=True)
        t1_root_child4.save(force_insert=True)

        t2 = Tree(alias='tree2')
        t2.save(force_insert=True)

        t2_root1 = TreeItem(title='{{ t2_root1_title }}', tree=t2, url='/')
        t2_root1.save(force_insert=True)

        t2_root2 = TreeItem(title='put {{ t2_root2_title }} inside', tree=t2, url='/sub/')
        t2_root2.save(force_insert=True)

        t2_root3 = TreeItem(title='for logged in only', tree=t2, url='/some/', access_loggedin=True)
        t2_root3.save(force_insert=True)

        cls.t1 = t1
        cls.t1_root = t1_root
        cls.t1_root_child1 = t1_root_child1
        cls.t1_root_child2 = t1_root_child2
        cls.t1_root_child3 = t1_root_child3
        cls.t1_root_child2_sub1 = t1_root_child2_sub1
        cls.t1_root_child2_sub2 = t1_root_child2_sub2

        cls.t2 = t2
        cls.t2_root1 = t2_root1

        cls.t2_root2 = t2_root2
        cls.t2_root3 = t2_root3

        # set urlconf to test's one
        cls.old_urlconf = urlresolvers.get_urlconf()
        urlresolvers.set_urlconf('sitetree.tests')
    def reset_urlresolvers_caches(self):
        # reset urlresolvers cache in order to update
        # urlpatterns provided by adminsite, to include
        # the just registered models
        if get_urlconf() is None:
            set_urlconf(settings.ROOT_URLCONF)

        reload_importlib_module(get_urlconf())
        clear_url_caches()
def get_response_with_exception_passthru(original_function, self, request):
    """
    Returns an HttpResponse object for the given HttpRequest. Unlike
    the original get_response, this does not catch exceptions, which
    allows you to see the full stack trace in your tests instead of
    a 500 error page.
    """
    
    # print("get_response(%s)" % request)
    
    from django.core import exceptions, urlresolvers
    from django.conf import settings

    # Setup default url resolver for this thread, this code is outside
    # the try/except so we don't get a spurious "unbound local
    # variable" exception in the event an exception is raised before
    # resolver is set
    urlconf = settings.ROOT_URLCONF
    urlresolvers.set_urlconf(urlconf)
    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
    response = None
    # Apply request middleware
    for middleware_method in self._request_middleware:
        response = middleware_method(request)
        if response:
            break

    if response is None:
        if hasattr(request, "urlconf"):
            # Reset url resolver with a custom urlconf.
            urlconf = request.urlconf
            urlresolvers.set_urlconf(urlconf)
            resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

        callback, callback_args, callback_kwargs = resolver.resolve(
                request.path_info)

        # Apply view middleware
        for middleware_method in self._view_middleware:
            response = middleware_method(request, callback, callback_args, callback_kwargs)
            if response:
                break

    if response is None:
        try:
            response = callback(request, *callback_args, **callback_kwargs)
        except Exception, e:
            # If the view raised an exception, run it through exception
            # middleware, and if the exception middleware returns a
            # response, use that. Otherwise, reraise the exception.
            for middleware_method in self._exception_middleware:
                response = middleware_method(request, e)
                if response:
                    break
            if response is None:
                raise
    def process_request(self, request):
        assert hasattr(request, 'session'), "You need to have the session app installed"
        
        # If the user agent is one we ignore, bail early
        request_user_agent = request.META.get('HTTP_USER_AGENT', '')
        for user_agent in USER_AGENT_BLACKLIST:
            if user_agent.search(request_user_agent):
                return
        
        # Mimic what django.core.base.BaseHandler does to resolve the request URL to a
        # callable
        from django.core import urlresolvers

        # Get urlconf from request object, if available.  Otherwise use default.
        urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
        try:
            try:
                callback, callback_args, callback_kwargs = resolver.resolve(
                        request.path_info)
            except SystemExit:
                raise
            except:
                # Meh, something went wrong in user code. Don't handle it here, 
                # it'll be handled later.
                return
        finally:
            # Reset URLconf for this thread on the way out for complete
            # isolation of request.urlconf. Only try this if the method
            # exists (which is the case for Django > 1.2)
            if hasattr(urlresolvers, 'set_urlconf'):
                urlresolvers.set_urlconf(None)
            
        # See if this view has been registered as one to skip user creation
        if not ALLOW_LAZY_REGISTRY.has_key(callback):
            return 
        
        # If there's already a key in the session for a valid user, then we don't 
        # need to do anything. If the user isn't valid, then get_user will return
        # an anonymous user.
        if not get_user(request).is_anonymous():
            return
            
        # If not, then we have to create a user, and log them in. Set the user id
        # in the session here to prevent the login call cycling the session key.
        username = request.session.session_key[:USERNAME_LENGTH]

        User.objects.create_user(username, '')
        request.user = None
        user = authenticate(username=username)
        assert user, "Lazy user creation and authentication failed. Have you got lazysignup.backends.LazySignupBackend in AUTHENTICATION_BACKENDS?"
        request.session[SESSION_KEY] = user.id
        login(request, user)

            
        
 def get_url_for_share(self, request):
     # Want to use a semi-canonical URL here
     if request.host.name == settings.DEFAULT_HOST:
         return self.get_absolute_url()
     else:
         current_urlconf = get_urlconf() or settings.ROOT_URLCONF
         set_urlconf(settings.ROOT_URLCONF)
         url = self.get_absolute_url()
         set_urlconf(current_urlconf)
         return url
    def test_request_urlconf_string(self):
        request = rf.get('/')
        set_urlconf('tests.urls')
        middleware = DebugToolbarMiddleware()

        middleware.process_request(request)

        patterns = get_resolver(get_urlconf()).url_patterns
        self.assertTrue(hasattr(patterns[1], '_callback_str'))
        self.assertEqual(patterns[-1]._callback_str, 'tests.views.execute_sql')
 def get_url_for_share(self, request):
     # Want to use a semi-canonical URL here
     if request.host.name == settings.DEFAULT_HOST:
         return self.get_absolute_url()
     else:
         current_urlconf = get_urlconf() or settings.ROOT_URLCONF
         set_urlconf(settings.ROOT_URLCONF)
         url = self.get_absolute_url()
         set_urlconf(current_urlconf)
         return url
    def get_resolver_args_and_kwargs(self):
        if hasattr(self.request, 'resolver_match'):
            _, args, kwargs = self.request.resolver_match
        else:
            urlconf = getattr(self.request, 'urlconf', settings.ROOT_URLCONF)
            urlresolvers.set_urlconf(urlconf)
            resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
            _, args, kwargs = resolver.resolve(self.request.path_info)

        return args, kwargs
    def setUpClass(cls):
        super(BlogPageTests, cls).setUpClass()

        User = get_user_model()

        Site.objects.get_or_create(id=settings.SITE_ID, defaults=dict(domain='django.localhost', name='django at localhost'))
        cls.user = User.objects.create_superuser("fluent-blogs-admin", '*****@*****.**', 'admin')

        # Testing with other URLconf, this works for every Django version
        cls._old_urlconf = get_urlconf()
        set_urlconf('fluent_blogs.pagetypes.blogpage.tests.urls')
Beispiel #40
0
    def test_using_not_default_urlconf(self):
        # Ensure that changing the currently active URLconf to something other
        # than the default still resolves wildcard subdomains correctly.
        set_urlconf(self.get_path_to_urlconf('api'))

        subdomain = 'wildcard'

        # This will raise NoReverseMatch if we're using the wrong URLconf for
        # the provided subdomain.
        self.assertEqual(reverse('application', subdomain=subdomain),
            'http://%s.%s/application/' % (subdomain, self.DOMAIN))
Beispiel #41
0
 def _urlconf_setup(self):
     set_urlconf(None)
     if hasattr(self, 'urls'):
         warnings.warn(
             "SimpleTestCase.urls is deprecated and will be removed in "
             "Django 2.0. Use @override_settings(ROOT_URLCONF=...) "
             "in %s instead." % self.__class__.__name__,
             RemovedInDjango20Warning, stacklevel=2)
         self._old_root_urlconf = settings.ROOT_URLCONF
         settings.ROOT_URLCONF = self.urls
         clear_url_caches()
Beispiel #42
0
    def test_using_not_default_urlconf(self):
        # Ensure that changing the currently active URLconf to something other
        # than the default still resolves wildcard subdomains correctly.
        set_urlconf(self.get_path_to_urlconf('api'))

        subdomain = 'wildcard'

        # This will raise NoReverseMatch if we're using the wrong URLconf for
        # the provided subdomain.
        self.assertEqual(reverse('application', subdomain=subdomain),
            'http://%s.%s/application/' % (subdomain, self.DOMAIN))
Beispiel #43
0
 def process_request(self, request):
     try:
         request.site = Site.objects.get(domain=request.get_host().lower().split(":")[0])
         request.urlconf = "sherpa.urls_%s" % request.site.template
         urlresolvers.set_urlconf(request.urlconf)
     except Site.DoesNotExist:
         # Unknown host name, redirect to the main site.
         # Rendering 404 in the main site's layout would probably also make sense, but don't do that for now since
         # all links will be relative and hence keep the incorrect host name.
         main_site = Site.objects.get(id=1)
         return redirect('http://%s/' % main_site.domain)
def reload_django_url_config():
    """
    Reloads Django's URL config.
    This is useful, for example, when a test enables new URLs
    with a django setting and the URL config needs to be refreshed.
    """
    urlconf = settings.ROOT_URLCONF
    if urlconf and urlconf in sys.modules:
        reload(sys.modules[urlconf])
    reloaded = import_module(urlconf)
    reloaded_urls = reloaded.urlpatterns
    set_urlconf(tuple(reloaded_urls))
Beispiel #45
0
def test_notification_reverse_url():
    try:
        set_urlconf("shuup_tests.notify.notification_test_urls")
        n = Notification()
        kwargs = dict(viewname="test", kwargs={"arg": "yes"})  # kwargs within kwargs, oh my
        n.set_reverse_url(**kwargs)
        n.save()
        with pytest.raises(ValueError):
            n.set_reverse_url()
        assert n.url == reverse(**kwargs)
    finally:
        set_urlconf(None)
Beispiel #46
0
def test_notification_reverse_url():
    try:
        set_urlconf("E-Commerce_tests.notify.notification_test_urls")
        n = Notification(shop=factories.get_default_shop())
        kwargs = dict(viewname="test", kwargs={"arg": "yes"})  # kwargs within kwargs, oh my
        n.set_reverse_url(**kwargs)
        n.save()
        with pytest.raises(ValueError):
            n.set_reverse_url()
        assert n.url == reverse(**kwargs)
    finally:
        set_urlconf(None)
Beispiel #47
0
    def pop(self, name):
        value = self._original_settings.get(name)

        if not value:
            return

        if value == NO_SETTING:
            delattr(settings, name)
        else:
            # special case
            if name == 'ROOT_URLCONF':
                set_urlconf(value)
            else:
                setattr(settings, name, value)
Beispiel #48
0
    def setUpClass(cls):
        cls.sitetree = SiteTree()

        t1 = Tree(alias='tree1')
        t1.save(force_insert=True)

        t1_root = TreeItem(title='root', tree=t1, url='/')
        t1_root.save(force_insert=True)

        t1_root_child1 = TreeItem(title='child1', tree=t1, parent=t1_root, url='/about/')
        t1_root_child1.save(force_insert=True)

        t1_root_child2 = TreeItem(title='child2', tree=t1, parent=t1_root, url='articles_list', urlaspattern=True)
        t1_root_child2.save(force_insert=True)

        t1_root_child2_sub1 = TreeItem(title='subchild1', tree=t1, parent=t1_root_child2,
            url='articles_detailed art_id', urlaspattern=True)
        t1_root_child2_sub1.save(force_insert=True)

        t1_root_child2_sub2 = TreeItem(title='subchild2', tree=t1, parent=t1_root_child2, url='/not_articles/10/')
        t1_root_child2_sub2.save(force_insert=True)

        t2 = Tree(alias='tree2')
        t2.save(force_insert=True)

        t2_root1 = TreeItem(title='{{ t2_root1_title }}', tree=t2, url='/')
        t2_root1.save(force_insert=True)

        t2_root2 = TreeItem(title='put {{ t2_root2_title }} inside', tree=t2, url='/sub/')
        t2_root2.save(force_insert=True)

        t2_root3 = TreeItem(title='for logged in only', tree=t2, url='/some/', access_loggedin=True)
        t2_root3.save(force_insert=True)

        cls.t1 = t1
        cls.t1_root = t1_root
        cls.t1_root_child1 = t1_root_child1
        cls.t1_root_child2 = t1_root_child2
        cls.t1_root_child2_sub1 = t1_root_child2_sub1
        cls.t1_root_child2_sub2 = t1_root_child2_sub2

        cls.t2 = t2
        cls.t2_root1 = t2_root1

        cls.t2_root2 = t2_root2
        cls.t2_root3 = t2_root3

        # set urlconf to test's one
        cls.old_urlconf = urlresolvers.get_urlconf()
        urlresolvers.set_urlconf('sitetree.tests')
Beispiel #49
0
    def setUpClass(cls):
        super(BlogPageTests, cls).setUpClass()

        User = get_user_model()

        Site.objects.get_or_create(id=settings.SITE_ID,
                                   defaults=dict(domain='django.localhost',
                                                 name='django at localhost'))
        cls.user = User.objects.create_superuser("fluent-blogs-admin",
                                                 '*****@*****.**', 'admin')

        # Testing with other URLconf, this works for every Django version
        cls._old_urlconf = get_urlconf()
        set_urlconf('fluent_blogs.pagetypes.blogpage.tests.urls')
Beispiel #50
0
    def process_request(self, request, cname_domain=False, partner_site=None):

        domain = get_domain(request)

        if is_rsr_instance(domain):
            urlconf = "akvo.urls.rsr"

        elif is_partner_site_instance(domain):
            urlconf = "akvo.urls.partner_sites"
            try:
                domain_parts = domain.split(".")
                hostname = domain_parts[0]
                if hostname == 'www':
                    hostname = domain_parts[1]

                partner_site = PartnerSite.objects.get(hostname=hostname)
            except:
                pass
            if partner_site is None or not partner_site.enabled:
                return redirect(PARTNER_SITES_MARKETING_SITE)

        else:  # Probably a partner site instance on partner-nominated domain
            cname_domain = True
            urlconf = "akvo.urls.partner_sites"
            try:
                partner_site = PartnerSite.objects.get(cname=domain)
            except:
                return redirect(PARTNER_SITES_MARKETING_SITE)

        request.urlconf = urlconf
        set_urlconf(urlconf)

        if partner_site is not None and partner_site.enabled:
            if cname_domain:
                partner_site_domain = getattr(settings, 'AKVOAPP_DOMAIN',
                                              'akvoapp.org')
            else:
                partner_site_domain = ".".join(domain.split(".")[1:])
            request.partner_site = settings.PARTNER_SITE = partner_site
            request.app_domain = ".".join(
                (partner_site.hostname, partner_site_domain))
            request.akvoapp_root_url = "http://%s" % request.app_domain
            request.organisation_id = partner_site.organisation.id
            request.default_language = partner_site.default_language

        request.domain_url = "http://%s" % settings.RSR_DOMAIN
        site = get_or_create_site(domain)
        settings.SITE_ID = site.id
        return
Beispiel #51
0
def send_activation_email(chef):
    """
    Send activation email to new user
    """
    cur_language = translation.get_language()
    translation.activate(chef.language)

    cur_urlconf = get_urlconf()
    set_urlconf('backend.urls')

    site = Site.objects.get_current()
    registration_profile = RegistrationProfile.objects.create_profile(chef)
    registration_profile.send_activation_email(site)

    set_urlconf(cur_urlconf)
    translation.activate(cur_language)
Beispiel #52
0
def send_welcome_email(chef):
    """
    Send welcome email to new user registered via FB
    """
    cur_language = translation.get_language()
    translation.activate(chef.language)

    cur_urlconf = get_urlconf()
    set_urlconf('backend.urls')

    site = Site.objects.get_current()
    registration_profile = RegistrationProfile.objects.create_profile(chef)
    RegistrationProfile.objects.activate_user(
        registration_profile.activation_key, site)

    set_urlconf(cur_urlconf)
    translation.activate(cur_language)
Beispiel #53
0
 def process_request(self, request):
     # Find best match, falling back to settings.DEFAULT_HOST
     host, kwargs = self.get_host(request.get_host())
     # This is the main part of this middleware
     request.urlconf = host.urlconf
     request.host = host
     # But we have to temporarily override the URLconf
     # already to allow correctly reversing host URLs in
     # the host callback, if needed.
     current_urlconf = get_urlconf()
     try:
         set_urlconf(host.urlconf)
         return host.callback(request, **kwargs)
     finally:
         # Reset URLconf for this thread on the way out for complete
         # isolation of request.urlconf
         set_urlconf(current_urlconf)
def render_region_card(context, region):
    from maps.widgets import map_options_for_region
    cache = get_cache('long-living')
    request = context['request']

    card = cache.get('rcard:%s' % region.id)
    if card:
        return card

    urlconf = get_urlconf()
    set_urlconf('main.urls')

    _file, _map, front_page_content = None, None, None
    is_meta_region = hasattr(
        region, 'regionsettings') and region.regionsettings.is_meta_region

    if Page.objects.filter(region=region, slug='front page'):
        front_page_content = Page.objects.get(region=region,
                                              slug='front page').content

    # User the cover photo, if it exists, as the thumbnail
    if FrontPage.objects.filter(region=region).exists():
        frontpage = FrontPage.objects.get(region=region)
        if frontpage.cover_photo:
            _file = frontpage.cover_photo

    # Otherwise, try and get a map
    if not _file and not is_meta_region and region.geom:
        map_opts = map_options_for_region(region)
        map_opts['default_zoom'] -= 1
        olwidget_options.update(map_opts)
        _map = InfoMap([(None, '')], options=olwidget_options).render(
            None, None, {'id': 'map_region_id_%s' % region.id})

    card = render_to_string(
        'cards/base.html', {
            'obj': region,
            'file': _file,
            'map': _map,
            'title': region.full_name,
            'content': front_page_content,
        })
    cache.set('rcard:%s' % region.id, card)

    set_urlconf(urlconf)
    return card
Beispiel #55
0
def set_urlconf_from_host(host):
    # Find best match, falling back to DEFAULT_SUBDOMAIN
    for subdomain in app_settings.SUBDOMAINS:
        match = subdomain['_regex'].match(host)
        if match:
            kwargs = match.groupdict()
            break
    else:
        kwargs = {}
        subdomain = get_subdomain(app_settings.DEFAULT_SUBDOMAIN)

    set_urlconf(subdomain['urlconf'])

    try:
        yield subdomain, kwargs
    finally:
        set_urlconf(None)
Beispiel #56
0
    def process_response(self, request, response):
        # Django resets the base urlconf when it starts to process
        # the response, so we need to set this again, in case
        # any of our middleware makes use of host, etc URLs.

        # Find best match, falling back to settings.DEFAULT_HOST
        try:
            host, kwargs = self.get_host(request.get_host())
        except DisallowedHost:
            # Bail out early, there is nothing to reset as HostsRequestMiddleware
            # never gets called with an invalid host.
            return response
        # This is the main part of this middleware
        request.urlconf = host.urlconf
        request.host = host

        set_urlconf(host.urlconf)
        return response
Beispiel #57
0
    def test_resolve(self):
        obj = TestPermalinkModel.objects.create()

        url = resolve('/r/{}-{}/'.format(
            ContentType.objects.get_for_model(TestPermalinkModel).pk, obj.pk))

        self.assertEqual(url, obj)

        with self.assertRaises(PermalinkError):
            # A valid URL, but not a permalink.
            resolve('/admin/')

        original_urlconf = urlresolvers.get_urlconf()
        with self.assertRaises(PermalinkError):
            urlresolvers.set_urlconf('cms.tests.urls')
            resolve('/r/')

        urlresolvers.set_urlconf(original_urlconf)
Beispiel #58
0
def dum_request():
    """
    Returns WSGIRequest object that is ready to be passed into a view
    """
    request_handler = _dum_client.handler
    environ = _dum_client._base_environ()

    request = WSGIRequest(environ)
    if request_handler._request_middleware is None:
        request_handler.load_middleware()

    urlconf = settings.ROOT_URLCONF
    urlresolvers.set_urlconf(urlconf)
    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
    try:
        response = None
        # Apply request middleware
        for middleware_method in request_handler._request_middleware:
            response = middleware_method(request)
            if response:
                break

        if response is None:
            if hasattr(request, 'urlconf'):
                # Reset url resolver with a custom urlconf.
                urlconf = request.urlconf
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

            resolver_match = resolver.resolve(request.path_info)
            callback, callback_args, callback_kwargs = resolver_match
            request.resolver_match = resolver_match

            # Apply view middleware
            for middleware_method in request_handler._view_middleware:
                response = middleware_method(
                    request, callback, callback_args, callback_kwargs
                )
                if response:
                    break
    except:
        pass
    finally:
        return request