Python django.core.urlresolvers.Resolver404() Examples

The following are 16 code examples of django.core.urlresolvers.Resolver404(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.urlresolvers , or try the search function .
Example #1
Source File: __init__.py    From decorate_url with GNU General Public License v3.0 6 votes vote down vote up
def resolve(self, path):
        path = force_text(path)
        tried = []
        match = self.regex.search(path)
        if match:
            new_path = path[match.end():]
            for pattern in self.url_patterns:
                try:
                    sub_match = pattern.resolve(new_path)
                except Resolver404 as e:
                    sub_tried = e.args[0].get('tried')
                    if sub_tried is not None:
                        tried.extend([pattern] + t for t in sub_tried)
                    else:
                        tried.append([pattern])
                else:
                    if sub_match:
                        sub_match_dict = dict(match.groupdict(), **self.default_kwargs)
                        sub_match_dict.update(sub_match.kwargs)
                        return ResolverMatch(self._decorate(sub_match.func), sub_match.args, sub_match_dict,
                                             sub_match.url_name, self.app_name or sub_match.app_name,
                                             [self.namespace] + sub_match.namespaces)
                    tried.append([pattern])
            raise Resolver404({'tried': tried, 'path': new_path})
        raise Resolver404({'path': path}) 
Example #2
Source File: serializers.py    From gro-api with GNU General Public License v2.0 6 votes vote down vote up
def to_internal_value(self, data):
        try:
            http_prefix = data.startswith(('http:', 'https:'))
        except AttributeError:
            self.fail('incorrect_type', data_type=type(data).__name__)

        if http_prefix:
            # If needed convert absolute URLs to relative path
            data = urlparse(data).path
            prefix = get_script_prefix()
            if data.startswith(prefix):
                data = '/' + data[len(prefix):]

        try:
            match = resolve(data)
        except Resolver404:
            self.fail('no_match')

        try:
            lookup_value = match.kwargs[self.lookup_url_kwarg]
            lookup_kwargs = {self.lookup_field: lookup_value}
            model = match.func.cls.model
            return model.objects.get(**lookup_kwargs)
        except (ObjectDoesNotExist, TypeError, ValueError):
            self.fail('does_not_exist') 
Example #3
Source File: admin_urls.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def add_preserved_filters(context, url, popup=False, to_field=None):
    opts = context.get('opts')
    preserved_filters = context.get('preserved_filters')

    parsed_url = list(urlparse(url))
    parsed_qs = dict(parse_qsl(parsed_url[4]))
    merged_qs = dict()

    if opts and preserved_filters:
        preserved_filters = dict(parse_qsl(preserved_filters))

        match_url = '/%s' % url.partition(get_script_prefix())[2]
        try:
            match = resolve(match_url)
        except Resolver404:
            pass
        else:
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            if changelist_url == current_url and '_changelist_filters' in preserved_filters:
                preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters']))

        merged_qs.update(preserved_filters)

    if popup:
        from django.contrib.admin.options import IS_POPUP_VAR
        merged_qs[IS_POPUP_VAR] = 1
    if to_field:
        from django.contrib.admin.options import TO_FIELD_VAR
        merged_qs[TO_FIELD_VAR] = to_field

    merged_qs.update(parsed_qs)

    parsed_url[4] = urlencode(merged_qs)
    return urlunparse(parsed_url) 
Example #4
Source File: resolution.py    From django-webmention with MIT License 5 votes vote down vote up
def url_resolves(url):
    try:
        resolve(urlparse(url).path)
    except Resolver404:
        return False
    return True 
Example #5
Source File: resolver.py    From django-telegram-bot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def resolve(self, update):
        try:
            resolver_match = self.resolver.resolve(update.message.text)
            return resolver_match
        except Resolver404:
            raise HandlerNotFound("No handler configured for  %s" % update.message.text) 
Example #6
Source File: middleware.py    From django-request-logging with MIT License 5 votes vote down vote up
def _should_log_route(self, request):
        # request.urlconf may be set by middleware or application level code.
        # Use this urlconf if present or default to None.
        # https://docs.djangoproject.com/en/2.1/topics/http/urls/#how-django-processes-a-request
        # https://docs.djangoproject.com/en/2.1/ref/request-response/#attributes-set-by-middleware
        urlconf = getattr(request, 'urlconf', None)

        try:
            route_match = resolve(request.path, urlconf=urlconf)
        except Resolver404:
            return False, None

        method = request.method.lower()
        view = route_match.func
        func = view
        # This is for "django rest framework"
        if hasattr(view, 'cls'):
            if hasattr(view, 'actions'):
                actions = view.actions
                method_name = actions.get(method)
                if method_name:
                    func = getattr(view.cls, view.actions[method], None)
            else:
                func = getattr(view.cls, method, None)
        elif hasattr(view, 'view_class'):
            # This is for django class-based views
            func = getattr(view.view_class, method, None)
        no_logging = getattr(func, NO_LOGGING_ATTR, False)
        no_logging_msg = getattr(func, NO_LOGGING_MSG_ATTR, None)
        return no_logging, no_logging_msg 
Example #7
Source File: bot.py    From permabots with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def handle_message(self, message, bot_service):
        """
        Process incoming message generating a response to the sender.
        
        :param message: Generic message received from provider
        :param bot_service: Service Integration
        :type bot_service: IntegrationBot :class:`IntegrationBot <permabots.models.bot.IntegrationBot>`

        .. note:: Message content will be extracted by IntegrationBot
        """
        urlpatterns = []
        state_context = {}
        chat_state = bot_service.get_chat_state(message)
        for handler in caching.get_or_set_related(self, 'handlers', 'response', 'request', 'target_state'):
            if handler.enabled:
                source_states = caching.get_or_set_related(handler, 'source_states')
                if chat_state:
                    state_context = chat_state.ctx
                if not source_states or (chat_state and chat_state.state in source_states):
                        urlpatterns.append(handler.urlpattern())
                    
        resolver = RegexURLResolver(r'^', urlpatterns)
        try:
            resolver_match = resolver.resolve(bot_service.message_text(message))
        except Resolver404:
            logger.warning("Handler not found for %s" % message)
        else:
            callback, callback_args, callback_kwargs = resolver_match
            logger.debug("Calling callback:%s for message %s with %s" % 
                         (callback, message, callback_kwargs))
            text, keyboard, target_state, context = callback(self, message=message, service=bot_service.identity, 
                                                             state_context=state_context, **callback_kwargs)
            if target_state:
                self.update_chat_state(bot_service, message, chat_state, target_state, context)
            keyboard = bot_service.build_keyboard(keyboard)
            bot_service.send_message(bot_service.get_chat_id(message), text, keyboard, message) 
Example #8
Source File: active_page.py    From cmdbac with Apache License 2.0 5 votes vote down vote up
def active_page(request, view_name):
    from django.core.urlresolvers import resolve, Resolver404
    if not request:
        return ""
    try:
        return "active" if resolve(request.path_info).url_name == view_name else ""
    except Resolver404:
        return "" 
Example #9
Source File: admin_urls.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def add_preserved_filters(context, url, popup=False, to_field=None):
    opts = context.get('opts')
    preserved_filters = context.get('preserved_filters')

    parsed_url = list(urlparse(url))
    parsed_qs = dict(parse_qsl(parsed_url[4]))
    merged_qs = dict()

    if opts and preserved_filters:
        preserved_filters = dict(parse_qsl(preserved_filters))

        match_url = '/%s' % url.partition(get_script_prefix())[2]
        try:
            match = resolve(match_url)
        except Resolver404:
            pass
        else:
            current_url = '%s:%s' % (match.app_name, match.url_name)
            changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name)
            if changelist_url == current_url and '_changelist_filters' in preserved_filters:
                preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters']))

        merged_qs.update(preserved_filters)

    if popup:
        from django.contrib.admin.options import IS_POPUP_VAR
        merged_qs[IS_POPUP_VAR] = 1
    if to_field:
        from django.contrib.admin.options import TO_FIELD_VAR
        merged_qs[TO_FIELD_VAR] = to_field

    merged_qs.update(parsed_qs)

    parsed_url[4] = urlencode(merged_qs)
    return urlunparse(parsed_url) 
Example #10
Source File: __init__.py    From django-websocket-request with MIT License 5 votes vote down vote up
def get_url_resolver_match(self):
        try:
            return resolve(self.url)
        except Resolver404:
            self.set_error('Resource not found.', 404) 
Example #11
Source File: views.py    From TWLight with MIT License 5 votes vote down vote up
def _is_real_url(url):
    """
    Users might have altered the URL parameters. Let's not just blindly
    redirect; let's actually make sure we can get somewhere first.
    """
    try:
        resolve(url)
        return True
    except Resolver404:
        return False 
Example #12
Source File: active_url_name.py    From connect with MIT License 5 votes vote down vote up
def add_active_url_name(request):
    """Function to add active URL name to the page context"""
    try:
        resolved = resolve(request.path_info)
        return {
            'active_url_name': resolved.url_name,
            'app_name': resolved.app_name
        }
    except Resolver404:
        return {} 
Example #13
Source File: test_active_url_name.py    From connect with MIT License 5 votes vote down vote up
def test_returns_nothing_with_error(self, mock):
        """Test that when a resolve fails an empty context is returned"""
        mock.side_effect = Resolver404()
        context = add_active_url_name(self.request)
        self.assertNotIn('active_url_name', context)
        self.assertNotIn('app_name', context) 
Example #14
Source File: debug.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        error_url = exception.args[0]['path']
    except (IndexError, TypeError, KeyError):
        error_url = request.path_info[1:]  # Trim leading slash

    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if (not tried                           # empty URLconf
            or (request.path == '/'
                and len(tried) == 1             # default URLconf
                and len(tried[0]) == 1
                and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')):
            return default_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    caller = ''
    try:
        resolver_match = resolve(request.path)
    except Resolver404:
        pass
    else:
        obj = resolver_match.func

        if hasattr(obj, '__name__'):
            caller = obj.__name__
        elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
            caller = obj.__class__.__name__

        if hasattr(obj, '__module__'):
            module = obj.__module__
            caller = '%s.%s' % (module, caller)

    t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE)
    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': error_url,
        'urlpatterns': tried,
        'reason': force_bytes(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
        'raising_view_name': caller,
    })
    return HttpResponseNotFound(t.render(c), content_type='text/html') 
Example #15
Source File: debug.py    From openhgsenti with Apache License 2.0 4 votes vote down vote up
def technical_404_response(request, exception):
    "Create a technical 404 error response. The exception should be the Http404."
    try:
        error_url = exception.args[0]['path']
    except (IndexError, TypeError, KeyError):
        error_url = request.path_info[1:]  # Trim leading slash

    try:
        tried = exception.args[0]['tried']
    except (IndexError, TypeError, KeyError):
        tried = []
    else:
        if (not tried                           # empty URLconf
            or (request.path == '/'
                and len(tried) == 1             # default URLconf
                and len(tried[0]) == 1
                and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')):
            return default_urlconf(request)

    urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
    if isinstance(urlconf, types.ModuleType):
        urlconf = urlconf.__name__

    caller = ''
    try:
        resolver_match = resolve(request.path)
    except Resolver404:
        pass
    else:
        obj = resolver_match.func

        if hasattr(obj, '__name__'):
            caller = obj.__name__
        elif hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
            caller = obj.__class__.__name__

        if hasattr(obj, '__module__'):
            module = obj.__module__
            caller = '%s.%s' % (module, caller)

    t = DEBUG_ENGINE.from_string(TECHNICAL_404_TEMPLATE)
    c = Context({
        'urlconf': urlconf,
        'root_urlconf': settings.ROOT_URLCONF,
        'request_path': error_url,
        'urlpatterns': tried,
        'reason': force_bytes(exception, errors='replace'),
        'request': request,
        'settings': get_safe_settings(),
        'raising_view_name': caller,
    })
    return HttpResponseNotFound(t.render(c), content_type='text/html') 
Example #16
Source File: middleware.py    From wagtailmodeladmin with MIT License 4 votes vote down vote up
def process_request(self, request):
        """
        Ignore unnecessary actions for static file requests, posts, or ajax
        requests. We're only interested in redirecting following a 'natural'
        request redirection to the `wagtailadmin_explore_root` or
        `wagtailadmin_explore` views.
        """
        referer_url = request.META.get('HTTP_REFERER')
        return_to_index_url = request.session.get('return_to_index_url')

        try:
            if all((
                return_to_index_url,
                referer_url,
                request.method == 'GET',
                not request.is_ajax(),
                resolve(request.path).url_name in ('wagtailadmin_explore_root',
                                                   'wagtailadmin_explore'),
            )):
                perform_redirection = False
                referer_match = resolve(urlparse(referer_url).path)
                if all((
                    referer_match.namespace == 'wagtailadmin_pages',
                    referer_match.url_name in (
                        'add',
                        'edit',
                        'delete',
                        'unpublish',
                        'copy'
                    ),
                )):
                    perform_redirection = True
                elif all((
                    not referer_match.namespace,
                    referer_match.url_name in (
                        'wagtailadmin_pages_create',
                        'wagtailadmin_pages_edit',
                        'wagtailadmin_pages_delete',
                        'wagtailadmin_pages_unpublish'
                    ),
                )):
                    perform_redirection = True
                if perform_redirection:
                    del request.session['return_to_index_url']
                    return HttpResponseRedirect(return_to_index_url)

        except Resolver404:
            pass

        return None