我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.urls.get_resolver()。
def _get_view_func(view): urlconf = get_urlconf() if get_resolver(urlconf)._is_callback(view): mod, func = get_mod_func(view) try: # Separate the module and function, e.g. # 'mymodule.views.myview' -> 'mymodule.views', 'myview'). return getattr(import_module(mod), func) except ImportError: # Import may fail because view contains a class name, e.g. # 'mymodule.views.ViewContainer.my_view', so mod takes the form # 'mymodule.views.ViewContainer'. Parse it again to separate # the module and class. mod, klass = get_mod_func(mod) return getattr(getattr(import_module(mod), klass), func) except AttributeError: # PY2 generates incorrect paths for views that are methods, # e.g. 'mymodule.views.ViewContainer.my_view' will be # listed as 'mymodule.views.my_view' because the class name # can't be detected. This causes an AttributeError when # trying to resolve the view. return None
def check_url_namespaces_unique(app_configs, **kwargs): """ Warn if URL namespaces used in applications aren't unique. """ if not getattr(settings, 'ROOT_URLCONF', None): return [] from django.urls import get_resolver resolver = get_resolver() all_namespaces = _load_all_namespaces(resolver) counter = Counter(all_namespaces) non_unique_namespaces = [n for n, count in counter.items() if count > 1] errors = [] for namespace in non_unique_namespaces: errors.append(Warning( "URL namespace '{}' isn't unique. You may not be able to reverse " "all URLs in this namespace".format(namespace), id="urls.W005", )) return errors
def get_context_data(self, **kwargs): view = self.kwargs['view'] urlconf = get_urlconf() if get_resolver(urlconf)._is_callback(view): mod, func = get_mod_func(view) view_func = getattr(import_module(mod), func) else: raise Http404 title, body, metadata = utils.parse_docstring(view_func.__doc__) if title: title = utils.parse_rst(title, 'view', _('view:') + view) if body: body = utils.parse_rst(body, 'view', _('view:') + view) for key in metadata: metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view) kwargs.update({ 'name': view, 'summary': title, 'body': body, 'meta': metadata, }) return super(ViewDetailView, self).get_context_data(**kwargs)
def check_url_config(app_configs, **kwargs): if getattr(settings, 'ROOT_URLCONF', None): from django.urls import get_resolver resolver = get_resolver() return check_resolver(resolver) return []
def get_response(self, request): """Return an HttpResponse object for the given HttpRequest.""" # Setup default url resolver for this thread set_urlconf(settings.ROOT_URLCONF) response = self._middleware_chain(request) # This block is only needed for legacy MIDDLEWARE_CLASSES; if # MIDDLEWARE is used, self._response_middleware will be empty. try: # Apply response middleware, regardless of the response for middleware_method in self._response_middleware: response = middleware_method(request, response) # Complain if the response middleware returned None (a common error). if response is None: raise ValueError( "%s.process_response didn't return an " "HttpResponse object. It returned None instead." % (middleware_method.__self__.__class__.__name__)) except Exception: # Any exception should be gathered and handled signals.got_request_exception.send(sender=self.__class__, request=request) response = self.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) response._closable_objects.append(request) # If the exception handler returns a TemplateResponse that has not # been rendered, force it to be rendered. if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)): response = response.render() if response.status_code == 404: logger.warning( 'Not Found: %s', request.path, extra={'status_code': 404, 'request': request}, ) return response
def is_language_prefix_patterns_used(urlconf): """ Return a tuple of two booleans: ( `True` if LocaleRegexURLResolver` is used in the `urlconf`, `True` if the default language should be prefixed ) """ for url_pattern in get_resolver(urlconf).url_patterns: if isinstance(url_pattern, LocaleRegexURLResolver): return True, url_pattern.prefix_default_language return False, False
def response_for_exception(request, exc): if isinstance(exc, Http404): if settings.DEBUG: response = debug.technical_404_response(request, exc) else: response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc) elif isinstance(exc, PermissionDenied): logger.warning( 'Forbidden (Permission denied): %s', request.path, extra={'status_code': 403, 'request': request}, ) response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc) elif isinstance(exc, MultiPartParserError): logger.warning( 'Bad request (Unable to parse request body): %s', request.path, extra={'status_code': 400, 'request': request}, ) response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SuspiciousOperation): if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent)): # POST data can't be accessed again, otherwise the original # exception would be raised. request._mark_post_parse_error() # The request logger receives events for any problematic request # The security logger receives events for all SuspiciousOperations security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__) security_logger.error( force_text(exc), extra={'status_code': 400, 'request': request}, ) if settings.DEBUG: response = debug.technical_500_response(request, *sys.exc_info(), status_code=400) else: response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SystemExit): # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise else: signals.got_request_exception.send(sender=None, request=request) response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) return response
def response_for_exception(request, exc): if isinstance(exc, Http404): if settings.DEBUG: response = debug.technical_404_response(request, exc) else: response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc) elif isinstance(exc, PermissionDenied): logger.warning( 'Forbidden (Permission denied): %s', request.path, extra={'status_code': 403, 'request': request}, ) response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc) elif isinstance(exc, MultiPartParserError): logger.warning( 'Bad request (Unable to parse request body): %s', request.path, extra={'status_code': 400, 'request': request}, ) response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SuspiciousOperation): if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent)): # POST data can't be accessed again, otherwise the original # exception would be raised. request._mark_post_parse_error() # The request logger receives events for any problematic request # The security logger receives events for all SuspiciousOperations security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__) security_logger.error( force_text(exc), extra={'status_code': 400, 'request': request}, ) if settings.DEBUG: response = debug.technical_500_response(request, *sys.exc_info(), status_code=400) else: response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SystemExit): # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise else: signals.got_request_exception.send(sender=None, request=request) response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) # Force a TemplateResponse to be rendered. if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)): response = response.render() return response
def response_for_exception(request, exc): if isinstance(exc, Http404): if settings.DEBUG: response = debug.technical_404_response(request, exc) else: response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc) elif isinstance(exc, PermissionDenied): logger.warning( 'Forbidden (Permission denied): %s', request.path, extra={'status_code': 403, 'request': request}, ) response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc) elif isinstance(exc, MultiPartParserError): logger.warning( 'Bad request (Unable to parse request body): %s', request.path, extra={'status_code': 400, 'request': request}, ) response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SuspiciousOperation): # The request logger receives events for any problematic request # The security logger receives events for all SuspiciousOperations security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__) security_logger.error( force_text(exc), extra={'status_code': 400, 'request': request}, ) if settings.DEBUG: response = debug.technical_500_response(request, *sys.exc_info(), status_code=400) else: response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc) elif isinstance(exc, SystemExit): # Allow sys.exit() to actually exit. See tickets #1023 and #4701 raise else: signals.got_request_exception.send(sender=None, request=request) response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) return response