django.conf.settings.ROOT_URLCONF

Here are the examples of the python api django.conf.settings.ROOT_URLCONF taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

126 Examples 7

Example 1

Project: localwiki-backend-server Source File: views.py
    @staticmethod
    def get_cache_key(*args, **kwargs):
        from django.core.urlresolvers import get_urlconf
        from pages.models import name_to_url
        import urllib
        urlconf = get_urlconf() or settings.ROOT_URLCONF
        region = CacheMixin.get_region_slug_param(*args, **kwargs)
        slug = kwargs.get('slug')
        # Control characters and whitespace not allowed in memcached keys
        date1 = name_to_url(kwargs.get('date1', ''))
        date2 = name_to_url(kwargs.get('date2', ''))
        version1 = name_to_url(kwargs.get('version1', ''))
        version2 = name_to_url(kwargs.get('version2', ''))
        return 'diff:%s/%s/%s/%s/%s/%s/%s' % (urlconf, name_to_url(region), date1, date2, version1, version2, slugify(slug).replace(' ', '_'))

Example 2

Project: django-statictemplate Source File: statictemplate.py
@contextmanager
def override_urlconf():
    has_old = hasattr(settings, 'ROOT_URLCONF')
    old = getattr(settings, 'ROOT_URLCONF', None)
    settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate'
    yield
    if has_old:
        setattr(settings, 'ROOT_URLCONF', old)
    else:  # NOQA
        delattr(settings, 'ROOT_URLCONF')

Example 3

Project: django-mini Source File: tests.py
    @patch('django.conf.settings')
    def test_configure_urlconf(self, settings):
        # Check our built-in URL module is configured.
        patterns = [(r'^test/', 'myapp.views.test')]
        djangomini.configure_urlconf(patterns)

        self.assertEqual(settings.ROOT_URLCONF, djangomini._rooturlconf)

Example 4

Project: synnefo Source File: volumes.py
Function: reload_url_conf
    def reload_urlconf(self):
        if 'synnefo.volume.urls' in sys.modules:
            reload(sys.modules['synnefo.volume.urls'])
        if settings.ROOT_URLCONF in sys.modules:
            reload(sys.modules[settings.ROOT_URLCONF])
        return import_module(settings.ROOT_URLCONF)

Example 5

Project: django Source File: views.py
Function: get_context_data
    def get_context_data(self, **kwargs):
        views = []
        urlconf = import_module(settings.ROOT_URLCONF)
        view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
        for (func, regex, namespace, name) in view_functions:
            views.append({
                'full_name': self._get_full_name(func),
                'url': simplify_regex(regex),
                'url_name': ':'.join((namespace or []) + (name and [name] or [])),
                'namespace': ':'.join((namespace or [])),
                'name': name,
            })
        kwargs.update({'views': views})
        return super(ViewIndexView, self).get_context_data(**kwargs)

Example 6

Project: avos Source File: helpers.py
    def _reload_urls(self):
        """CLeans up URLs.

        Clears out the URL caches, reloads the root urls module, and
        re-triggers the autodiscovery mechanism for Horizon. Allows URLs
        to be re-calculated after registering new dashboards. Useful
        only for testing and should never be used on a live site.
        """
        urlresolvers.clear_url_caches()
        reload(import_module(settings.ROOT_URLCONF))
        base.Horizon._urls()

Example 7

Project: cabot Source File: test_urlprefix.py
Function: clear_cache
    def clear_cache(self):
        # If we don't do this, nothing gets correctly set for the URL Prefix
        urlconf = settings.ROOT_URLCONF
        if urlconf in sys.modules:
            reload(sys.modules[urlconf])
        import_module(urlconf)

        # Don't forget to clear out the cache for `reverse`
        clear_url_caches()

Example 8

Project: splunk-webframework Source File: jsurls.py
def create_javascript_urlpatterns():
    js_patterns = SortedDict()
    handle_url_module(js_patterns, settings.ROOT_URLCONF)
    
    dirpath = path.join(settings.STATIC_ROOT, settings.JS_CACHE_DIR)
    filepath = path.join(settings.STATIC_ROOT, settings.JS_CACHE_DIR, "urlresolver.js")
    
    tmpl = loader.get_template('splunkdj:jsurls.html')
    ctx = Context({ 'patterns': json.dumps(js_patterns), 'mount': settings.MOUNT })
    rendered = tmpl.render(ctx)
    
    if not path.exists(dirpath):
        makedirs(dirpath)
    
    output_file = open(filepath, 'w')
    output_file.write(rendered)
    output_file.flush()
    
    output_file.close()

Example 9

Project: opps Source File: middleware.py
    def process_request(self, request):
        """
        if the requested site is id 2 it
        will force the ROOT_URLCONF = 'yourproject.urls_2.py'
        """
        self.request = request
        site = get_current_site(request)
        if site.id > 1:
            prefix = "_{0}".format(site.id)
            self.request.urlconf = settings.ROOT_URLCONF + prefix

Example 10

Project: django-rest-framework Source File: schemas.py
Function: init
    def __init__(self, patterns=None, urlconf=None):
        if patterns is None:
            if urlconf is None:
                # Use the default Django URL conf
                urlconf = settings.ROOT_URLCONF

            # Load the given URLconf module
            if isinstance(urlconf, six.string_types):
                urls = import_module(urlconf)
            else:
                urls = urlconf
            patterns = urls.urlpatterns

        self.patterns = patterns

Example 11

Project: django-widgy Source File: middleware.py
Function: process_request
    def process_request(self, request):
        root_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        if isinstance(root_urlconf, six.string_types):
            root_urlconf = import_module(root_urlconf)
        request.urlconf = self.get_urlconf(root_urlconf, self.get_pages(logged_in=request.user.is_authenticated()))
        request._patch_urlconf_middleware_urlconf = request.urlconf

Example 12

Project: django-oscar Source File: guest_checkout_tests.py
Function: reload_url_conf
def reload_url_conf():
    # Reload URLs to pick up the overridden settings
    if settings.ROOT_URLCONF in sys.modules:
        reload(sys.modules[settings.ROOT_URLCONF])
    import_module(settings.ROOT_URLCONF)
    clear_url_caches()

Example 13

Project: cgstudiomap Source File: urlresolvers.py
Function: get_resolver
@lru_cache.lru_cache(maxsize=None)
def get_resolver(urlconf=None):
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    return RegexURLResolver(r'^/', urlconf)

Example 14

Project: localwiki-backend-server Source File: views.py
    @staticmethod
    def get_cache_key(*args, **kwargs):
        from django.core.urlresolvers import get_urlconf
        from pages.models import name_to_url

        urlconf = get_urlconf() or settings.ROOT_URLCONF
        region = CacheMixin.get_region_slug_param(*args, **kwargs)
        # Control characters and whitespace not allowed in memcached keys
        return 'map:%s/%s/main_map' % (urlconf, name_to_url(region))

Example 15

Project: django-compositepks Source File: testcases.py
Function: post_teardown
    def _post_teardown(self):
        """ Performs any post-test things. This includes:

            * Putting back the original ROOT_URLCONF if it was changed.
        """
        if hasattr(self, '_old_root_urlconf'):
            settings.ROOT_URLCONF = self._old_root_urlconf
            clear_url_caches()

Example 16

Project: localwiki-backend-server Source File: urlresolvers.py
Function: reverse
def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None):
    original_kwargs = kwargs
    if urlconf is None:
        urlconf = get_urlconf() or settings.ROOT_URLCONF
        # We behave differently if we're using the no-region urlconf with the
        # no-region django-hosts host.
        if urlconf == 'main.urls_no_region':
            if kwargs and kwargs.get('region'):
                del kwargs['region']
    try:
        return django_reverse(viewname, urlconf=urlconf, args=args, kwargs=kwargs, prefix=prefix, current_app=current_app)
    except NoReverseMatch as e:
        if urlconf == 'main.urls_no_region':
            # Try the base urlconf and original kwargs
            host = settings.DEFAULT_HOST
            return reverse_full(host, viewname, view_args=args, view_kwargs=original_kwargs)
        else:
            raise e

Example 17

Project: decode-Django Source File: urlresolvers.py
Function: get_resolver
def get_resolver(urlconf):
    # 如果为空, 导入 settings 中的 ROOT_URLCONF
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    return RegexURLResolver(r'^/', urlconf)

Example 18

Project: theyworkforyou Source File: urlresolvers.py
Function: resolve
def resolve(path, urlconf=None):
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    resolver = RegexURLResolver(r'^/', urlconf)
    return resolver.resolve(path)

Example 19

Project: theyworkforyou Source File: urlresolvers.py
Function: reverse
def reverse(viewname, urlconf=None, args=None, kwargs=None):
    args = args or []
    kwargs = kwargs or {}
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    resolver = RegexURLResolver(r'^/', urlconf)
    return '/' + resolver.reverse(viewname, *args, **kwargs)

Example 20

Project: horizon Source File: helpers.py
    def _reload_urls(self):
        """CLeans up URLs.

        Clears out the URL caches, reloads the root urls module, and
        re-triggers the autodiscovery mechanism for Horizon. Allows URLs
        to be re-calculated after registering new dashboards. Useful
        only for testing and should never be used on a live site.
        """
        urlresolvers.clear_url_caches()
        moves.reload_module(import_module(settings.ROOT_URLCONF))
        base.Horizon._urls()

Example 21

Project: django-cms Source File: test_apphooks.py
Function: reload_urls
    def reload_urls(self):
        from django.conf import settings

        url_modules = [
            'cms.urls',
            'cms.test_utils.project.second_cms_urls_for_apphook_tests',
            settings.ROOT_URLCONF,
        ]

        clear_app_resolvers()
        clear_url_caches()

        for module in url_modules:
            if module in sys.modules:
                del sys.modules[module]

Example 22

Project: django-cms Source File: apphook_reload.py
Function: reload_url_conf
def reload_urlconf(urlconf=None, new_revision=None):
    from cms.appresolver import clear_app_resolvers, get_app_patterns

    if 'cms.urls' in sys.modules:
        reload(sys.modules['cms.urls'])
    if urlconf is None:
        urlconf = settings.ROOT_URLCONF
    if urlconf in sys.modules:
        reload(sys.modules[urlconf])
    clear_app_resolvers()
    clear_url_caches()
    get_app_patterns()
    if new_revision is not None:
        set_local_revision(new_revision)

Example 23

Project: jmbo Source File: items.py
Function: is_active
    def is_active(self, request):
        urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
        resolver = RegexURLResolver(r'^/', urlconf)

        url_name = self.resolve_pattern_name(resolver, request.path)
        return url_name in self.matching_pattern_names

Example 24

Project: django Source File: locale.py
Function: process_request
    def process_request(self, request):
        urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
        i18n_patterns_used, prefixed_default_language = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(request, check_path=i18n_patterns_used)
        language_from_path = translation.get_language_from_path(request.path_info)
        if not language_from_path and i18n_patterns_used and not prefixed_default_language:
            language = settings.LANGUAGE_CODE
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()

Example 25

Project: transurlvania Source File: urlresolvers.py
Function: get_resolver
def get_resolver(urlconf, lang):
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    key = (urlconf, lang)
    if key not in _resolvers:
        _resolvers[key] = MultilangRegexURLResolver(r'^/', urlconf)
    return _resolvers[key]

Example 26

Project: soapfish Source File: django_test.py
    def setUp(self):  # noqa
        # XXX: Python 2.6 and unittest2 still call this method for skipped class.
        if django is None:
            self.skipTest('Django is not installed.')

        self.service = echo_service()
        settings.ROOT_URLCONF = urlconf(urlpatterns=(url(r'^ws/$', django_dispatcher(self.service)),))
        self.client = Client()

Example 27

Project: django-pki Source File: middleware.py
Function: resolver
def resolver(request):
    """
    Returns a RegexURLResolver for the request's urlconf.

    If the request does not have a urlconf object, then the default of
    settings.ROOT_URLCONF is used.
    """
    from django.conf import settings
    urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
    return RegexURLResolver(r'^/', urlconf)

Example 28

Project: canvas Source File: middleware.py
    def process_request(self, request):
        if self.show_toolbar(request):
            if self.override_url:
                original_urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
                debug_toolbar.urls.urlpatterns += patterns('',
                    ('', include(original_urlconf)),
                )
                self.override_url = False
            request.urlconf = 'debug_toolbar.urls'

            self.debug_toolbars[request] = DebugToolbar(request)
            for panel in self.debug_toolbars[request].panels:
                panel.process_request(request)

Example 29

Project: django-widgy Source File: signalhandlers.py
@receiver(widgy_pre_index)
def patch_url_conf(sender, **kwargs):
    from .middleware import PatchUrlconfMiddleware
    root_urlconf = import_module(settings.ROOT_URLCONF)
    urlconf = PatchUrlconfMiddleware.get_urlconf(root_urlconf)
    set_urlconf(urlconf)

Example 30

Project: PyClassLessons Source File: urlresolvers.py
Function: get_resolver
@lru_cache.lru_cache(maxsize=None)
def get_resolver(urlconf):
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    return RegexURLResolver(r'^/', urlconf)

Example 31

Project: ANALYSE Source File: tests.py
Function: test_render_to_string_when_no_global_context_cms
    @unittest.skipUnless(settings.ROOT_URLCONF == 'cms.urls', 'Test only valid in cms')
    @patch("edxmako.middleware.REQUEST_CONTEXT")
    def test_render_to_string_when_no_global_context_cms(self, context_mock):
        """
        Test render_to_string() when makomiddleware has not initialized
        the threadlocal REQUEST_CONTEXT.context. This is meant to run in CMS.
        """
        del context_mock.context
        self.assertIn("We're having trouble rendering your component", render_to_string("html_error.html", None))

Example 32

Project: avos Source File: base.py
Function: reload_urls
    def _reload_urls(self):
        """Clears out the URL caches, reloads the root urls module, and
        re-triggers the autodiscovery mechanism for Horizon. Allows URLs
        to be re-calculated after registering new dashboards. Useful
        only for testing and should never be used on a live site.
        """
        urlresolvers.clear_url_caches()
        reload(import_module(settings.ROOT_URLCONF))
        base.Horizon._urls()

Example 33

Project: localwiki-backend-server Source File: cache.py
def varnish_invalidate_page(p):
    current_urlconf = get_urlconf() or settings.ROOT_URLCONF

    if p.region.regionsettings.domain:
        # Has a domain, ugh. Need to clear two URLs on two hosts, in this case
        set_urlconf('main.urls_no_region')
        varnish_invalidate_url(p.get_absolute_url(), hostname=p.region.regionsettings.domain)

        # Now invalidate main path on LocalWiki hub
        set_urlconf('main.urls')
        varnish_invalidate_url(p.get_absolute_url())
    else:
        varnish_invalidate_url(p.get_absolute_url())

    set_urlconf(current_urlconf)

Example 34

Project: horizon Source File: base.py
Function: reload_urls
    def _reload_urls(self):
        """Clears out the URL caches, reloads the root urls module, and
        re-triggers the autodiscovery mechanism for Horizon. Allows URLs
        to be re-calculated after registering new dashboards. Useful
        only for testing and should never be used on a live site.
        """
        urlresolvers.clear_url_caches()
        moves.reload_module(import_module(settings.ROOT_URLCONF))
        base.Horizon._urls()

Example 35

Project: localwiki-backend-server Source File: views.py
    @staticmethod
    def get_cache_key(*args, **kwargs):
        from django.core.urlresolvers import get_urlconf
        from pages.models import name_to_url

        urlconf = get_urlconf() or settings.ROOT_URLCONF
        slug = kwargs.get('slug')
        region = CacheMixin.get_region_slug_param(*args, **kwargs)
        # Control characters and whitespace not allowed in memcached keys
        return 'tags:%s/%s/%s' % (urlconf, name_to_url(region), slugify(slug).replace(' ', '_'))

Example 36

Project: hue Source File: testcases.py
    def _urlconf_setup(self):
        set_urlconf(None)
        if hasattr(self, 'urls'):
            self._old_root_urlconf = settings.ROOT_URLCONF
            settings.ROOT_URLCONF = self.urls
            clear_url_caches()

Example 37

Project: django-rest-framework-docs Source File: api_docs.py
Function: init
    def __init__(self, drf_router=None):
        self.endpoints = []
        self.drf_router = drf_router
        try:
            root_urlconf = import_string(settings.ROOT_URLCONF)
        except ImportError:
            # Handle a case when there's no dot in ROOT_URLCONF
            root_urlconf = import_module(settings.ROOT_URLCONF)
        if hasattr(root_urlconf, 'urls'):
            self.get_all_view_names(root_urlconf.urls.urlpatterns)
        else:
            self.get_all_view_names(root_urlconf.urlpatterns)

Example 38

Project: django-daydreamer Source File: base.py
Function: get_resolver
    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)

Example 39

Project: airmozilla Source File: test_views.py
    def _get_handler500(self):
        root_urlconf = __import__(settings.ROOT_URLCONF,
                                  globals(), locals(), ['urls'], -1)
        # ...so that we can access the 'handler500' defined in there
        par, end = root_urlconf.handler500.rsplit('.', 1)
        # ...which is an importable reference to the real handler500 function
        views = __import__(par, globals(), locals(), [end], -1)
        # ...and finally we the handler500 function at hand
        return getattr(views, end)

Example 40

Project: django-mini Source File: djangomini.py
def configure_urlconf(patterns):
    """Sets up Django's settings.ROOT_URLCONF patterns."""
    from django.conf import settings

    # Has to be hashable or a string naming a module.
    # Make a real module for compatibility.
    mod = imp.new_module(_rooturlconf)
    mod.urlpatterns = patterns
    sys.modules[_rooturlconf] = mod
    settings.ROOT_URLCONF = _rooturlconf

Example 41

Project: tendenci Source File: helpers.py
Function: reload_url_conf
def reload_urlconf(urlconf=None):

    from imp import reload  # python 3 needs this import.

    if urlconf is None:
        from django.conf import settings

        urlconf = settings.ROOT_URLCONF

    if HELPDESK_URLCONF in sys.modules:
        reload(sys.modules[HELPDESK_URLCONF])

    if urlconf in sys.modules:
        reload(sys.modules[urlconf])

    from django.core.urlresolvers import clear_url_caches
    clear_url_caches()

Example 42

Project: talk.org Source File: tests.py
    def setUp(self):
        settings.ROOT_URLCONF = 'django.contrib.formtools.test_urls'
        # Create a FormPreview instance to share between tests
        self.preview = preview.FormPreview(TestForm)
        input_template = '<input type="hidden" name="%s" value="%s" />'
        self.input = input_template % (self.preview.unused_name('stage'), "%d")

Example 43

Project: PyClassLessons Source File: views.py
Function: get_context_data
    def get_context_data(self, **kwargs):
        views = []
        urlconf = import_module(settings.ROOT_URLCONF)
        view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
        for (func, regex, namespace, name) in view_functions:
            views.append({
                'full_name': '%s.%s' % (func.__module__, getattr(func, '__name__', func.__class__.__name__)),
                'url': simplify_regex(regex),
                'url_name': ':'.join((namespace or []) + (name and [name] or [])),
                'namespace': ':'.join((namespace or [])),
                'name': name,
            })
        kwargs.update({'views': views})
        return super(ViewIndexView, self).get_context_data(**kwargs)

Example 44

Project: dynamic-models Source File: utils.py
def reregister_in_admin(admin_site, model, admin_class=None):
    " (re)registers a dynamic model in the given admin site "

    # We use our own unregister, to ensure that the correct
    # existing model is found 
    # (Django's unregister doesn't expect the model class to change)
    unregister_from_admin(admin_site, model)
    admin_site.register(model, admin_class)

    # Reload the URL conf and clear the URL cache
    # It's important to use the same string as ROOT_URLCONF
    reload(import_module(settings.ROOT_URLCONF))
    clear_url_caches()

Example 45

Project: aldryn-events Source File: base.py
Function: reload_urls
    def reload_urls(self):
        """
        Clean up url related things (caches, app resolvers, modules).
        Taken from cms.
        :return: None
        """
        clear_app_resolvers()
        clear_url_caches()
        url_modules = [
            'cms.urls',
            'aldryn_events.urls',
            settings.ROOT_URLCONF
        ]

        for module in url_modules:
            if module in sys.modules:
                del sys.modules[module]

Example 46

Project: pytest-django Source File: plugin.py
@pytest.fixture(autouse=True, scope='function')
def _django_set_urlconf(request):
    """Apply the @pytest.mark.urls marker, internal to pytest-django."""
    marker = request.keywords.get('urls', None)
    if marker:
        skip_if_no_django()
        import django.conf
        from django.core.urlresolvers import clear_url_caches, set_urlconf

        validate_urls(marker)
        original_urlconf = django.conf.settings.ROOT_URLCONF
        django.conf.settings.ROOT_URLCONF = marker.urls
        clear_url_caches()
        set_urlconf(None)

        def restore():
            django.conf.settings.ROOT_URLCONF = original_urlconf
            # Copy the pattern from
            # https://github.com/django/django/blob/master/django/test/signals.py#L152
            clear_url_caches()
            set_urlconf(None)

        request.addfinalizer(restore)

Example 47

Project: talk.org Source File: debug.py
Function: technical_404_response
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError):
        tried = []
    else:
        if not tried:
            # tried exists but is an empty list. The URLconf must've been empty.
            return empty_urlconf(request)

    t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
    c = Context({
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': request.path[1:], # Trim leading slash
        'urlpatterns': tried,
        'reason': str(exception),
        'request': request,
        'request_protocol': request.is_secure() and "https" or "http",
        'settings': get_safe_settings(),
    })
    return HttpResponseNotFound(t.render(c), mimetype='text/html')

Example 48

Project: talk.org Source File: base.py
Function: get_response
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django.core import exceptions, urlresolvers
        from django.core.mail import mail_admins
        from django.conf import settings

        # Apply request middleware
        for middleware_method in self._request_middleware:
            response = middleware_method(request)
            if response:
                return response

        # Get urlconf from request object, if available.  Otherwise use default.
        urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)

        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
        try:
            callback, callback_args, callback_kwargs = resolver.resolve(request.path)

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

            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:
                        return response
                raise

            # Complain if the view returned None (a common error).
            if response is None:
                try:
                    view_name = callback.func_name # If it's a function
                except AttributeError:
                    view_name = callback.__class__.__name__ + '.__call__' # If it's a class
                raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)

            return response
        except http.Http404, e:
            if settings.DEBUG:
                from django.views import debug
                return debug.technical_404_response(request, e)
            else:
                callback, param_dict = resolver.resolve404()
                return callback(request, **param_dict)
        except exceptions.PermissionDenied:
            return http.HttpResponseForbidden('<h1>Permission denied</h1>')
        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise
        except: # Handle everything else, including SuspiciousOperation, etc.
            # Get the exception info now, in case another exception is thrown later.
            exc_info = sys.exc_info()
            receivers = dispatcher.send(signal=signals.got_request_exception, request=request)
            if settings.DEBUG:
                from django.views import debug
                return debug.technical_500_response(request, *exc_info)
            else:
                # When DEBUG is False, send an error message to the admins.
                subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)
                try:
                    request_repr = repr(request)
                except:
                    request_repr = "Request repr() unavailable"
                message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr)
                mail_admins(subject, message, fail_silently=True)
                # Return an HttpResponse that displays a friendly error message.
                callback, param_dict = resolver.resolve500()
                return callback(request, **param_dict)

Example 49

Project: GAE-Bulk-Mailer Source File: base.py
Function: get_response
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        try:
            # 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)
            try:
                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)

                    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 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 as 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

                # Complain if the view returned None (a common error).
                if response is None:
                    if isinstance(callback, types.FunctionType):    # FBV
                        view_name = callback.__name__
                    else:                                           # CBV
                        view_name = callback.__class__.__name__ + '.__call__'
                    raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response
                if hasattr(response, 'render') and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()

            except http.Http404 as e:
                logger.warning('Not Found: %s', request.path,
                            extra={
                                'status_code': 404,
                                'request': request
                            })
                if settings.DEBUG:
                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except:
                        signals.got_request_exception.send(sender=self.__class__, request=request)
                        response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
            except exceptions.PermissionDenied:
                logger.warning(
                    'Forbidden (Permission denied): %s', request.path,
                    extra={
                        'status_code': 403,
                        'request': request
                    })
                try:
                    callback, param_dict = resolver.resolve403()
                    response = callback(request, **param_dict)
                except:
                    signals.got_request_exception.send(
                            sender=self.__class__, request=request)
                    response = self.handle_uncaught_exception(request,
                            resolver, sys.exc_info())
            except SystemExit:
                # Allow sys.exit() to actually exit. See tickets #1023 and #4701
                raise
            except: # Handle everything else, including SuspiciousOperation, etc.
                # Get the exception info now, in case another exception is thrown later.
                signals.got_request_exception.send(sender=self.__class__, request=request)
                response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
        finally:
            # Reset URLconf for this thread on the way out for complete
            # isolation of request.urlconf
            urlresolvers.set_urlconf(None)

        try:
            # Apply response middleware, regardless of the response
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        except: # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        return response

Example 50

Project: talk.org Source File: urlresolvers.py
Function: get_resolver
def get_resolver(urlconf):
    if urlconf is None:
        from django.conf import settings
        urlconf = settings.ROOT_URLCONF
    return RegexURLResolver(r'^/', urlconf)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3