当前位置: 首页>>代码示例>>Python>>正文


Python urlresolvers.Resolver404方法代码示例

本文整理汇总了Python中django.core.urlresolvers.Resolver404方法的典型用法代码示例。如果您正苦于以下问题:Python urlresolvers.Resolver404方法的具体用法?Python urlresolvers.Resolver404怎么用?Python urlresolvers.Resolver404使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.urlresolvers的用法示例。


在下文中一共展示了urlresolvers.Resolver404方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: resolve

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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}) 
开发者ID:vorujack,项目名称:decorate_url,代码行数:27,代码来源:__init__.py

示例2: to_internal_value

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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') 
开发者ID:OpenAgricultureFoundation,项目名称:gro-api,代码行数:27,代码来源:serializers.py

示例3: add_preserved_filters

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:37,代码来源:admin_urls.py

示例4: url_resolves

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
def url_resolves(url):
    try:
        resolve(urlparse(url).path)
    except Resolver404:
        return False
    return True 
开发者ID:easy-as-python,项目名称:django-webmention,代码行数:8,代码来源:resolution.py

示例5: resolve

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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) 
开发者ID:jlmadurga,项目名称:django-telegram-bot,代码行数:8,代码来源:resolver.py

示例6: _should_log_route

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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 
开发者ID:Rhumbix,项目名称:django-request-logging,代码行数:32,代码来源:middleware.py

示例7: handle_message

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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) 
开发者ID:jlmadurga,项目名称:permabots,代码行数:38,代码来源:bot.py

示例8: active_page

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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 "" 
开发者ID:cmu-db,项目名称:cmdbac,代码行数:10,代码来源:active_page.py

示例9: get_url_resolver_match

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
def get_url_resolver_match(self):
        try:
            return resolve(self.url)
        except Resolver404:
            self.set_error('Resource not found.', 404) 
开发者ID:GetBlimp,项目名称:django-websocket-request,代码行数:7,代码来源:__init__.py

示例10: _is_real_url

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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 
开发者ID:WikipediaLibrary,项目名称:TWLight,代码行数:12,代码来源:views.py

示例11: add_active_url_name

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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 {} 
开发者ID:ofa,项目名称:connect,代码行数:12,代码来源:active_url_name.py

示例12: test_returns_nothing_with_error

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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) 
开发者ID:ofa,项目名称:connect,代码行数:8,代码来源:test_active_url_name.py

示例13: technical_404_response

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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') 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:54,代码来源:debug.py

示例14: process_request

# 需要导入模块: from django.core import urlresolvers [as 别名]
# 或者: from django.core.urlresolvers import Resolver404 [as 别名]
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 
开发者ID:rkhleics,项目名称:wagtailmodeladmin,代码行数:52,代码来源:middleware.py


注:本文中的django.core.urlresolvers.Resolver404方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。