我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用django.core.urlresolvers.Resolver404()。
def assert_model_resolves_expected_view(self, obj, expected_view): """Check if expected view is called for the given obj's absolute_url In some cases an earlier defined url in the urls.py catches the request. For class-based views give function returned by `as_view()` as expected_view. """ url = obj.get_absolute_url() try: view, args, kwargs = resolve(url) except Resolver404: raise AssertionError('Unable to resolve the url for the object: "{url}"'.format(url=url)) self.assertEqual( expected_view, view, msg="Url resolves to {view} instead of the expected {expected_view}.".format(view=view, expected_view=expected_view) )
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})
def get_via_uri(self, uri, request=None): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``. Optionally accepts a ``request``. If you need custom behavior based on other portions of the URI, simply override this method. """ prefix = get_script_prefix() chomped_uri = uri if prefix and chomped_uri.startswith(prefix): chomped_uri = chomped_uri[len(prefix)-1:] try: view, args, kwargs = resolve(chomped_uri) except Resolver404: raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri) bundle = self.build_bundle(request=request) return self.obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs)) # Data preparation.
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)
def process_request(self, request): try: resolver_match = self.resolver.resolve(request.path_info) except Resolver404: return None callback, callback_args, callback_kwargs = resolver_match request.resolver_match = resolver_match return callback(request, *callback_args, **callback_kwargs)
def url(self): url = self.get('ic-current-url', None) match = None if url is not None: url = url.strip() url = urlparse(url) if url.path: try: match = resolve(url.path) except Resolver404: pass return UrlMatch(url, match)
def _is_account_url(request): try: url_name = resolve(request.path).url_name except Resolver404: return False return any(url_name == url.name for url in account_urls.urlpatterns)
def render(self, context): url = None # get the page number we're linking to from the context page_num = self.page_num.resolve(context) try: # determine what view we are using based upon the path of this page view, args, kwargs = resolve(context['request'].path) except (Resolver404, KeyError) as err: print err raise ValueError('Invalid pagination page.') else: # set the page parameter for this view kwargs['page'] = page_num # get the new URL from Django url = reverse(view, args=args, kwargs=kwargs) if self.varname: # if we have a varname, put the URL into the context and return nothing context[self.varname] = url return '' # otherwise, return the URL directly return url
def is_admin_request(request): try: return resolve(request.path).app_name == 'admin' except Resolver404: return False
def in_apphook(self): with force_language(self.toolbar.language): try: resolver = resolve(self.request.path_info) except Resolver404: return False else: from cms.views import details return resolver.func != details
def _handle_no_page(request, slug): context = {} context['cms_version'] = __version__ context['cms_edit_on'] = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') if not slug and settings.DEBUG: return TemplateResponse(request, "cms/welcome.html", context) try: #add a $ to the end of the url (does not match on the cms anymore) resolve('%s$' % request.path) except Resolver404 as e: # raise a django http 404 page exc = Http404(dict(path=request.path, tried=e.args[0]['tried'])) raise exc raise Http404('CMS Page not found: %s' % request.path)
def active_page(request, view_name, **kwargs): from django.core.urlresolvers import resolve, Resolver404 path = resolve(request.path_info) if not request: return "" try: if path.url_name == view_name and path.kwargs == kwargs: return "active" else: return "" except Resolver404: return ""
def clean_slug(self): slug = self.cleaned_data['slug'] if slug.startswith("_"): raise forms.ValidationError( ugettext('A slug may not begin with an underscore.')) if slug == 'admin': raise forms.ValidationError( ugettext("'admin' is not a permitted slug name.")) if settings.URL_CASE_SENSITIVE: already_existing_slug = models.URLPath.objects.filter( slug=slug, parent=self.urlpath_parent) else: slug = slug.lower() already_existing_slug = models.URLPath.objects.filter( slug__iexact=slug, parent=self.urlpath_parent) if already_existing_slug: already_urlpath = already_existing_slug[0] if already_urlpath.article and already_urlpath.article.current_revision.deleted: raise forms.ValidationError( ugettext('A deleted article with slug "%s" already exists.') % already_urlpath.slug) else: raise forms.ValidationError( ugettext('A slug named "%s" already exists.') % already_urlpath.slug) if settings.CHECK_SLUG_URL_AVAILABLE: try: # Fail validation if URL resolves to non-wiki app match = resolve(self.urlpath_parent.path + '/' + slug + '/') if match.app_name != 'wiki': raise forms.ValidationError( ugettext('This slug conflicts with an existing URL.')) except Resolver404: pass return slug
def add_preserved_filters(context, url, popup=False): 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)) try: match = resolve(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 merged_qs.update(parsed_qs) parsed_url[4] = urlencode(merged_qs) return urlunparse(parsed_url)
def get_via_uri(self, uri, request=None): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``. Optionally accepts a ``request``. If you need custom behavior based on other portions of the URI, simply override this method. """ prefix = get_script_prefix() chomped_uri = uri if prefix and chomped_uri.startswith(prefix): chomped_uri = chomped_uri[len(prefix)-1:] try: view, args, kwargs = resolve(chomped_uri) resource_name = kwargs['resource_name'] resource_class = self.resource_mapping[resource_name] except (Resolver404, KeyError): raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri) parent_resource = resource_class(api_name=self._meta.api_name) kwargs = parent_resource.remove_api_resource_names(kwargs) bundle = Bundle(request=request) return parent_resource.obj_get(bundle, **kwargs)
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)
def sanitize_next(request): """ Get appropriate next value for the given request """ try: url_name = resolve(request.path).url_name except Resolver404: url_name = '__invalid_url_name__' if url_name in _get_account_url_names(): nextparam = request.GET.get('next') or request.POST.get('next') next = nextparam if is_safe_url(nextparam) else '/' else: next = request.get_full_path() return next
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)
def is_allowed_homepage(url_string): """return True is the current page can be set as homepage""" url = urlparse.urlparse(url_string) try: safe_url = url.path resolved = resolve(safe_url) except Resolver404: return False if resolved.url_name in get_allowed_homepages(): return True return False
def to_internal_value(self, data): """ TODO - I've had to copy this method from HyperlinkedRelatedField purely so that it can deal with polymorphic models. This probably is not ideal. """ 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.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') if self._serializer_is_polymorphic: # TODO - This is not really what we want. Need to make sure # that match.view_name points to a view which uses a subtype # serializer for this polymorphic serializer self.view_name = match.view_name if match.view_name != self.view_name: self.fail('incorrect_match') try: return self.get_object(match.view_name, match.args, match.kwargs) except (ObjectDoesNotExist, TypeError, ValueError): self.fail('does_not_exist')
def view_passes_test(view_name, path, **kwargs): # Special case for tag included everywhere if view_name == '__all__': return True try: view = resolve(path, **kwargs) return view_name == view.view_name except Resolver404: return False
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')
def __init__(self, request): super(CMSToolbar, self).__init__() self.right_items = [] self.left_items = [] self.populated = False self.post_template_populated = False self.menus = {} self.obj = None self.redirect_url = None self.request = None self.is_staff = None self.edit_mode = None self.edit_mode_url_on = get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON') self.edit_mode_url_off = get_cms_setting('CMS_TOOLBAR_URL__EDIT_OFF') self.disable_url = get_cms_setting('CMS_TOOLBAR_URL__DISABLE') self.build_mode = None self.use_draft = None self.show_toolbar = None self.login_form = None self.clipboard = None self.language = None self.toolbar_language = None self.simple_structure_mode = get_cms_setting('TOOLBAR_SIMPLE_STRUCTURE_MODE') self.show_toolbar = True self.init_toolbar(request) with force_language(self.language): try: decorator = resolve(self.request.path_info).func try: # If the original view is decorated we try to extract the real function # module instead of the decorator's one if decorator and getattr(decorator, 'func_closure', False): # python 2 self.app_name = decorator.func_closure[0].cell_contents.__module__ elif decorator and getattr(decorator, '__closure__', False): # python 3 self.app_name = decorator.__closure__[0].cell_contents.__module__ else: raise AttributeError() except (TypeError, AttributeError): # no decorator self.app_name = decorator.__module__ except Resolver404: self.app_name = "" toolbars = toolbar_pool.get_toolbars() parts = self.app_name.split('.') while parts: path = '.'.join(parts) if path in installed_apps(): self.app_name = path break parts.pop() self.toolbars = OrderedDict() for key in toolbars: toolbar = toolbars[key](self.request, self, toolbars[key].check_current_app(key, self.app_name), self.app_name) self.toolbars[key] = toolbar