我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用django.urls.get_urlconf()。
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 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 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 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
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()) # 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 async_get_response_dj_1_10(self, request): """This is the get_response function copied directly from Django 1.10.0""" """With the addition of async compatibility""" """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) if isawaitable(response): response = await response try: # Apply response middleware, regardless of the response for middleware_method in self._response_middleware: response = middleware_method(request, response) if isawaitable(response): response = await 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 isawaitable(response): response = await response if response.status_code == 404: logger.warning( 'Not Found: %s', request.path, extra={'status_code': 404, 'request': request}, ) return response