def test_process_site_1(self):
        request = RequestFactory(host='www.example.com').get('/')
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls1')

        request = RequestFactory(host='alias1.example.com').get('/')
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls1')
Exemplo n.º 2
0
def test_override_urlconf_when_exception(current, override):
    set_urlconf(current)
    assert get_urlconf() == current
    try:
        with override_urlconf(override):
            assert get_urlconf() == override
            raise Exception('something went wrong')
    except Exception as err:
        assert str(err) == 'something went wrong'
    assert get_urlconf() == current
Exemplo n.º 3
0
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 test_process_reponse(self):
        request = RequestFactory(host='www.example2.com').get('/')
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls2')
        CMSMultiSiteMiddleware().process_response(request, HttpResponse(''))
        # Default is restored after request is processed
        self.assertIsNone(get_urlconf())

        request = RequestFactory(host='alias2.example2.com').get('/')
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls2')
        CMSMultiSiteMiddleware().process_response(request, HttpResponse(''))
        # Default is restored after request is processed
        self.assertIsNone(get_urlconf())
    def test_process_site_2(self):
        request = RequestFactory(host='www.example2.com').get('/')
        DynamicSiteMiddleware().process_request(request)
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls2')

        request = RequestFactory(host='alias2.example2.com').get('/')
        DynamicSiteMiddleware().process_request(request)
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls2')

        # aliases not configured on django-multisite will not be recognizes
        request = RequestFactory(host='alias3.example2.com').get('/')
        with self.assertRaises(Http404):
            DynamicSiteMiddleware().process_request(request)
Exemplo n.º 6
0
    def override_settings(ROOT_URLCONF=None):
        assert get_urlconf() == ROOT_URLCONF

        def dummy_dec(func):
            return func

        return dummy_dec
Exemplo n.º 7
0
def _get_patterns(matcher: Callable[[APIView], bool],
                  patterns: Optional[list] = None,
                  prefix=""):
    """Find a subset of URL patterns, based on a matching predicate."""
    if patterns is None:
        resolver = get_resolver(get_urlconf())
        patterns = resolver.url_patterns

    matches = []

    # This code is inspired by DRF's EndpointEnumerator.get_api_endpoints().
    # However, instead of returning the paths, it collects the URL patterns.
    for pattern in patterns:
        path_regex = f"{prefix}{pattern.pattern}"
        if isinstance(pattern, URLPattern):
            # Inspect the class-based-view for inclusion
            if hasattr(pattern.callback, "cls") and matcher(
                    pattern.callback.cls):
                matches.append(pattern)

        elif isinstance(pattern, URLResolver):
            # Recurse into the 'include' section to find matches.
            sub_patterns = _get_patterns(matcher,
                                         patterns=pattern.url_patterns,
                                         prefix=path_regex)
            if sub_patterns:
                # Return a root object, but only include the objects that matched.
                root = copy(pattern)
                root.__dict__["url_patterns"] = sub_patterns
                matches.append(root)
        else:
            raise NotImplementedError(f"Unknown URL pattern type: {pattern!r}")

    return matches
Exemplo n.º 8
0
def response_for_exception(request, exc):
    '''simplified from Django 1.11 source.
    The difference is that we use the exception that was passed in,
    rather than referencing sys.exc_info(), which gives us the ResponseForException
    the original exception was wrapped in, which we don't want to show to users.
        '''
    if isinstance(exc, UNHANDLED_EXCEPTIONS):
        '''copied from Django source, but i don't think these
        exceptions will actually occur.'''
        raise exc
    signals.got_request_exception.send(sender=None, request=request)
    exc_info = (type(exc), exc, exc.__traceback__)
    response = handle_uncaught_exception(request, get_resolver(get_urlconf()), exc_info)
    log_response(
        '%s: %s',
        response.reason_phrase,
        request.path,
        response=response,
        request=request,
        exc_info=exc,
    )
    if settings.DEBUG:
        response_content = response.content.split(b'<div id="requestinfo">')[0]
        response_content += TECHNICAL_500_AUTORELOAD_JS
        response.content = response_content

    # Force a TemplateResponse to be rendered.
    if not getattr(response, 'is_rendered', True) and callable(
        getattr(response, 'render', None)
    ):
        response = response.render()

    return response
Exemplo n.º 9
0
def track_request_view_data(request, tracked_request):
    path = request.path
    tracked_request.tag(
        "path",
        create_filtered_path(path, [(k, v) for k, vs in request.GET.lists()
                                    for v in vs]),
    )
    if ignore_path(path):
        tracked_request.tag("ignore_transaction", True)

    if scout_config.value("collect_remote_ip"):
        try:
            # Determine a remote IP to associate with the request. The value is
            # spoofable by the requester so this is not suitable to use in any
            # security sensitive context.
            user_ip = (request.META.get("HTTP_X_FORWARDED_FOR",
                                        "").split(",")[0]
                       or request.META.get("HTTP_CLIENT_IP", "").split(",")[0]
                       or request.META.get("REMOTE_ADDR", None))
            tracked_request.tag("user_ip", user_ip)
        except Exception:
            pass

    user = getattr(request, "user", None)
    if user is not None:
        try:
            tracked_request.tag("username", user.get_username())
        except Exception:
            pass

    tracked_request.tag("urlconf", get_urlconf(settings.ROOT_URLCONF))
Exemplo n.º 10
0
def get_redirect(request):
    # 重定向
    # return redirect('/get_render')
    # return redirect(Student)  模型名
    # return redirect(get_render) 视图名

    # 上下结果一样。都能实现重定向

    # 实例化一个响应对象
    # response = Response()
    # response.status_code = 307
    # response['Location'] = '/get_render'
    # return response

    # import app01
    # urls.path('/zbc', app01.views.get_render)
    # return redirect('zbc')

    # 通过视图名找到视图对应的uri
    print(urls.reverse(get_attr_by_request))


    # 获取所有数据
    infors = Student.objects.filter(id=1)
    print(infors)
    # 获取当前项目的uri跟视图映射的文件
    print(urls.get_urlconf())

    return HttpResponse('aaa')
Exemplo n.º 11
0
    def validate_local_url(self, value):
        value = self.clean_url(value)
        # If we have i18n pattern in the URLconf, by default it will be
        # resolved against default language by `LocaleRegexURLResolver`. In
        # this case, it won't resolve the path /de/catalogue/ when default
        # language code is "en-gb" and so that path validation won't pass,
        # which is incorrect. In order to work it around, we extract language
        # code from URL and override current locale within the locale prefix of
        # the URL.
        #
        # 如果我们在URLconf中有i18n模式,默认情况下它将通过`LocaleRegexURLResolver`解析
        # 为默认语言。 在这种情况下,当默认语言代码为“en-gb”时,它将不会解析路
        # 径/ de / catalog /,因此路径验证将不会通过,这是不正确的。 为了解决这个问题,
        # 我们从URL中提取语言代码并覆盖URL的语言环境前缀中的当前语言环境。

        urlconf = get_urlconf()
        i18n_patterns_used, _ = is_language_prefix_patterns_used(urlconf)
        redefined_language = None
        if i18n_patterns_used:
            language = get_language_from_path(value)
            current_language = get_language()
            if language != current_language:
                redefined_language = language
        if redefined_language:
            with override(redefined_language):
                self._validate_url(value)
        else:
            self._validate_url(value)
Exemplo n.º 12
0
    def get_form(self, request, obj=None, **kwargs):
        """Returns modified form for TreeItem model.
        'Parent' field choices are built by sitetree itself.

        """
        if obj is not None and obj.parent is not None:
            self.previous_parent = obj.parent
            previous_parent_id = self.previous_parent.id
        else:
            previous_parent_id = None

        my_choice_field = TreeItemChoiceField(self.tree, initial=previous_parent_id)
        form = super(TreeItemAdmin, self).get_form(request, obj, **kwargs)
        my_choice_field.label = form.base_fields['parent'].label
        my_choice_field.help_text = form.base_fields['parent'].help_text
        # Replace 'parent' TreeItem field with new appropriate one
        form.base_fields['parent'] = my_choice_field

        # Try to resolve all currently registered url names including those in namespaces.
        if not getattr(self, 'known_url_names', False):
            self.known_url_names = []
            self.known_url_rules = []
            resolver = get_resolver(get_urlconf())
            for ns, (url_prefix, ns_resolver) in resolver.namespace_dict.items():
                if ns != 'admin':
                    self._stack_known_urls(ns_resolver.reverse_dict, ns)
            self._stack_known_urls(resolver.reverse_dict)
            self.known_url_rules = sorted(self.known_url_rules)

        form.known_url_names_hint = _(
            'You are seeing this warning because "URL as Pattern" option is active and pattern entered above '
            'seems to be invalid. Currently registered URL pattern names and parameters: ')
        form.known_url_names = self.known_url_names
        form.known_url_rules = self.known_url_rules
        return form
Exemplo n.º 13
0
    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)

        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
Exemplo n.º 14
0
def get_all_remote_methods(resolver=None, ns_prefix=''):
    """
    Returns a dictionary to be used for calling ``djangoCall.configure()``, which itself extends the
    Angular API to the client, offering him to call remote methods.
    """
    if not resolver:
        resolver = get_resolver(get_urlconf())
    result = {}
    for name in resolver.reverse_dict.keys():
        if not isinstance(name, six.string_types):
            continue
        try:
            url = reverse(ns_prefix + name)
            resmgr = resolve(url)
            ViewClass = import_string('{0}.{1}'.format(resmgr.func.__module__,
                                                       resmgr.func.__name__))
            if isclass(ViewClass) and issubclass(ViewClass, JSONResponseMixin):
                result[name] = _get_remote_methods_for(ViewClass, url)
        except (NoReverseMatch, ImproperlyConfigured):
            pass
    for namespace, ns_pattern in resolver.namespace_dict.items():
        sub_res = get_all_remote_methods(ns_pattern[1],
                                         ns_prefix + namespace + ':')
        if sub_res:
            result[namespace] = sub_res
    return result
Exemplo n.º 15
0
def track_request_view_data(request, tracked_request):
    path = request.path
    tracked_request.tag(
        "path",
        create_filtered_path(path, [(k, v) for k, vs in request.GET.lists()
                                    for v in vs]),
    )
    if ignore_path(path):
        tracked_request.tag("ignore_transaction", True)

    if scout_config.value("collect_remote_ip"):
        try:
            # Determine a remote IP to associate with the request. The value is
            # spoofable by the requester so this is not suitable to use in any
            # security sensitive context.
            user_ip = (request.META.get("HTTP_X_FORWARDED_FOR",
                                        "").split(",")[0]
                       or request.META.get("HTTP_CLIENT_IP", "").split(",")[0]
                       or request.META.get("REMOTE_ADDR", None))
            tracked_request.tag("user_ip", user_ip)
        except Exception:
            pass

    # Django's request.user caches in this attribute on first access. We only
    # want to track the user if the application code has touched request.user
    # because touching it causes session access, which adds "Cookie" to the
    # "Vary" header.
    user = getattr(request, "_cached_user", None)
    if user is not None:
        try:
            tracked_request.tag("username", user.get_username())
        except Exception:
            pass

    tracked_request.tag("urlconf", get_urlconf(settings.ROOT_URLCONF))
Exemplo n.º 16
0
def views_module(namespace):
    urlconf = get_urlconf()
    resolver = get_resolver(urlconf)
    _, sub_resolver = resolver.namespace_dict[namespace]
    if hasattr(sub_resolver.urlconf_module, 'views'):
        return sub_resolver.urlconf_module.views
    return None
Exemplo n.º 17
0
    def get_form(self, request, obj=None, **kwargs):
        """Returns modified form for TreeItem model.
        'Parent' field choices are built by sitetree itself.

        """
        if obj is not None and obj.parent is not None:
            self.previous_parent = obj.parent

        form = super().get_form(request, obj, **kwargs)
        form.base_fields['parent'].choices_init(self.tree)

        # Try to resolve all currently registered url names including those in namespaces.
        if not getattr(self, 'known_url_names', False):
            self.known_url_names = []
            self.known_url_rules = []

            resolver = get_resolver(get_urlconf())

            for ns, (url_prefix,
                     ns_resolver) in resolver.namespace_dict.items():
                if ns != 'admin':
                    self._stack_known_urls(ns_resolver.reverse_dict, ns)

            self._stack_known_urls(resolver.reverse_dict)
            self.known_url_rules = sorted(self.known_url_rules)

        form.known_url_names_hint = _(
            'You are seeing this warning because "URL as Pattern" option is active and pattern entered above '
            'seems to be invalid. Currently registered URL pattern names and parameters: '
        )

        form.known_url_names = self.known_url_names
        form.known_url_rules = self.known_url_rules

        return form
Exemplo n.º 18
0
    def __call__(self, request):
        try:
            response = self.get_response(request)
        except Http404 as exc:
            if settings.DEBUG:
                response = debug.technical_404_response(request, exc)
            else:
                response = self.handler.get_exception_response(request, get_resolver(get_urlconf()), 404, exc)

        except PermissionDenied as exc:
            logger.warning(
                'Forbidden (Permission denied): %s', request.path,
                extra={'status_code': 403, 'request': request},
            )
            response = self.handler.get_exception_response(request, get_resolver(get_urlconf()), 403, exc)

        except MultiPartParserError as exc:
            logger.warning(
                'Bad request (Unable to parse request body): %s', request.path,
                extra={'status_code': 400, 'request': request},
            )
            response = self.handler.get_exception_response(request, get_resolver(get_urlconf()), 400, exc)

        except SuspiciousOperation as exc:
            # 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:
                return debug.technical_500_response(request, *sys.exc_info(), status_code=400)

            response = self.handler.get_exception_response(request, get_resolver(get_urlconf()), 400, exc)

        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        except Exception:  # Handle everything else.
            # Get the exception info now, in case another exception is thrown later.
            signals.got_request_exception.send(sender=self.handler.__class__, request=request)
            response = self.handler.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())

        return response
Exemplo n.º 19
0
    def test_process_site_2(self):
        request = RequestFactory(host='www.example2.com').get('/')
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls2')

        request = RequestFactory(host='alias2.example2.com').get('/')
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls2')

        # don't set port in MULTISITE_CMS_ALIASES, otherwise it will not be matched
        request = RequestFactory(host='alias3.example2.com').get('/')
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls1')

        # don't set port in MULTISITE_CMS_ALIASES, otherwise it will not be matched
        request = RequestFactory(host='alias3.example2.com:8000').get('/')
        CMSMultiSiteMiddleware().process_request(request)
        self.assertEqual(get_urlconf(), 'tests.test_utils.urls1')
Exemplo n.º 20
0
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
Exemplo n.º 21
0
def override_urlconf(new_urlconf):
    """
    Context manager for temporarily overriding the urlconf for the current
    thread.
    """
    original_urlconf = get_urlconf()
    set_urlconf(new_urlconf)
    try:
        yield
    finally:
        set_urlconf(original_urlconf)
Exemplo n.º 22
0
def get_site_dict(app_name='filebrowser'):
    """
    Return a dict with all *deployed* FileBrowser sites that have
    a given app_name.
    """
    if app_name not in _sites_cache:
        return {}
    # Get names of all deployed filebrowser sites with a give app_name
    deployed = get_resolver(get_urlconf()).app_dict[app_name]
    # Get the deployed subset from the cache
    return dict((k, v) for k, v in _sites_cache[app_name].items() if k in deployed)
Exemplo n.º 23
0
    def get(self, request):
        """
        Return a list of all the installed OAuth modules
        """
        extra, resolver = get_resolver( get_urlconf()).namespace_dict['oauth_manager']

        installed_apps = resolver.app_dict.keys()

        module_links =  [{'application' : oauth_module, 'url' : reverse( 'oauth_manager:{0}:schema'.format(oauth_module) )} for oauth_module in installed_apps ]

        return Response({ 'links' : module_links } )
Exemplo n.º 24
0
def reload_urlconf(urlconf_name=None):
    if urlconf_name is None:
        urlconf_name = get_urlconf() or settings.ROOT_URLCONF

    # Reload the global top-level module
    if urlconf_name in sys.modules:
        reload(sys.modules[urlconf_name])
    else:
        import_module(urlconf_name)

    # Clear the Django lru caches
    clear_url_caches()
Exemplo n.º 25
0
def get_urls_details():
    """Return a list with the models names."""
    patterns = []
    _get_url_patterns(get_resolver(get_urlconf()), patterns, "")
    res = {}
    for i in patterns:
        info = {
            "url_name": i["pattern"].name,
            "pattern": i["url"],
        }
        info.update(_get_callback_info(i["pattern"].callback))
        res[i["pattern"].name] = info
    return res
    async 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
Exemplo n.º 27
0
 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)
Exemplo n.º 28
0
def get_default_site(app_name='filebrowser'):
    """
    Returns the default site. This function uses Django's url resolution method to
    obtain the name of the default site.
    """
    # Get the name of the default site:
    resolver = get_resolver(get_urlconf())
    name = 'filebrowser'

    # Django's default name resolution method (see django.core.urlresolvers.reverse())
    app_list = resolver.app_dict[app_name]
    if name not in app_list:
        name = app_list[0]

    return get_site_dict()[name]
def get_default_site(app_name='filebrowser'):
    """
    Returns the default site. This function uses Django's url resolution method to
    obtain the name of the default site.
    """
    # Get the name of the default site:
    resolver = get_resolver(get_urlconf())
    name = 'filebrowser'

    # Django's default name resolution method (see django.core.urlresolvers.reverse())
    app_list = resolver.app_dict[app_name]
    if name not in app_list:
        name = app_list[0]

    return get_site_dict()[name]
Exemplo n.º 30
0
 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)
Exemplo n.º 31
0
 def inner(request):
     try:
         response = get_response(request)
     except TimeoutError as exc:
         log.warning(
             f'Timeout: {request.path}',
             extra={
                 'status_code': 408,
                 'request': request
             },
         )
         resolver = get_resolver(get_urlconf())
         response = get_exception_response(request, resolver, 408, exc)
     except Exception as exc:
         response = response_for_exception(request, exc)
     return response
Exemplo n.º 32
0
 def get_context_data(self, **kwargs):
     views = []
     url_resolver = get_resolver(get_urlconf())
     try:
         view_functions = extract_views_from_urlpatterns(url_resolver.url_patterns)
     except ImproperlyConfigured:
         view_functions = []
     for (func, regex, namespace, name) in view_functions:
         views.append({
             'full_name': get_view_name(func),
             'url': simplify_regex(regex),
             'url_name': ':'.join((namespace or []) + (name and [name] or [])),
             'namespace': ':'.join(namespace or []),
             'name': name,
         })
     return super().get_context_data(**{**kwargs, 'views': views})
Exemplo n.º 33
0
def urltemplate_namespaces(viewname, current_app=None, *args, **kwargs):
    urlconf = urls.get_urlconf()
    resolver = urls.get_resolver(urlconf)
    prefix = urls.get_script_prefix()

    parts = viewname.split(':')
    parts.reverse()
    view = parts[0]
    path = parts[1:]

    resolved_path = []
    ns_pattern = ''
    while path:
        ns = path.pop()

        # Lookup the name to see if it could be an app identifier
        try:
            app_list = resolver.app_dict[ns]
            # Yes! Path part matches an app in the current Resolver
            if current_app and current_app in app_list:
                # If we are reversing for a particular app,
                # use that namespace
                ns = current_app
            elif ns not in app_list:
                # The name isn't shared by one of the instances
                # (i.e., the default) so just pick the first instance
                # as the default.
                ns = app_list[0]
        except KeyError:
            pass

        try:
            extra, resolver = resolver.namespace_dict[ns]
            resolved_path.append(ns)
            ns_pattern = ns_pattern + extra
        except KeyError as key:
            if resolved_path:
                raise urls.NoReverseMatch(
                    "%s is not a registered namespace inside '%s'" %
                    (key, ':'.join(resolved_path)))
            else:
                raise urls.NoReverseMatch("%s is not a registered namespace" %
                                          key)
    if ns_pattern:
        resolver = urls.get_ns_resolver(ns_pattern, resolver)

    return urltemplate_with_prefix(resolver, view, prefix, *args, **kwargs)
Exemplo n.º 34
0
 def process_request(self, request):
     # Find best match, falling back to settings.DEFAULT_HOST
     host, kwargs = self.get_host(request.get_host())
     # This is the main part of this middleware
     request.urlconf = host.urlconf
     request.host = host
     # But we have to temporarily override the URLconf
     # already to allow correctly reversing host URLs in
     # the host callback, if needed.
     current_urlconf = get_urlconf()
     try:
         set_urlconf(host.urlconf)
         return host.callback(request, **kwargs)
     finally:
         # Reset URLconf for this thread on the way out for complete
         # isolation of request.urlconf
         set_urlconf(current_urlconf)
Exemplo n.º 35
0
 def process_request(self, request):
     # Find best match, falling back to settings.DEFAULT_HOST
     host, kwargs = self.get_host(request.get_host())
     # This is the main part of this middleware
     request.urlconf = host.urlconf
     request.host = host
     # But we have to temporarily override the URLconf
     # already to allow correctly reversing host URLs in
     # the host callback, if needed.
     current_urlconf = get_urlconf()
     try:
         set_urlconf(host.urlconf)
         return host.callback(request, **kwargs)
     finally:
         # Reset URLconf for this thread on the way out for complete
         # isolation of request.urlconf
         set_urlconf(current_urlconf)
Exemplo n.º 36
0
    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
Exemplo n.º 37
0
 def validate_local_url(self, value):
     value = self.clean_url(value)
     # If we have i18n pattern in the URLconf, by default it will be
     # resolved against default language by `LocaleRegexURLResolver`. In
     # this case, it won't resolve the path /de/catalogue/ when default
     # language code is "en-gb" and so that path validation won't pass,
     # which is incorrect. In order to work it around, we extract language
     # code from URL and override current locale within the locale prefix of
     # the URL.
     urlconf = get_urlconf()
     i18n_patterns_used, _ = is_language_prefix_patterns_used(urlconf)
     redefined_language = None
     if i18n_patterns_used:
         language = get_language_from_path(value)
         current_language = get_language()
         if language != current_language:
             redefined_language = language
     if redefined_language:
         with override(redefined_language):
             self._validate_url(value)
     else:
         self._validate_url(value)
Exemplo n.º 38
0
Arquivo: views.py Projeto: 01-/django
 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)
Exemplo n.º 39
0
 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
Exemplo n.º 40
0
def get_all_remote_methods(resolver=None, ns_prefix=''):
    """
    Returns a dictionary to be used for calling ``djangoCall.configure()``, which itself extends the
    Angular API to the client, offering him to call remote methods.
    """
    if not resolver:
        resolver = get_resolver(get_urlconf())
    result = {}
    for name in resolver.reverse_dict.keys():
        if not isinstance(name, six.string_types):
            continue
        try:
            url = reverse(ns_prefix + name)
            resmgr = resolve(url)
            ViewClass = import_string('{0}.{1}'.format(resmgr.func.__module__, resmgr.func.__name__))
            if isclass(ViewClass) and issubclass(ViewClass, JSONResponseMixin):
                result[name] = _get_remote_methods_for(ViewClass, url)
        except (NoReverseMatch, ImproperlyConfigured):
            pass
    for namespace, ns_pattern in resolver.namespace_dict.items():
        sub_res = get_all_remote_methods(ns_pattern[1], ns_prefix + namespace + ':')
        if sub_res:
            result[namespace] = sub_res
    return result
Exemplo n.º 41
0
 def override_settings(ROOT_URLCONF=None):
     assert get_urlconf() == ROOT_URLCONF
     def dummy_dec(func):
         return func
     return dummy_dec
Exemplo n.º 42
0
def test_override_urlconf(current, override):
    set_urlconf(current)
    assert get_urlconf() == current
    with override_urlconf(override):
        assert get_urlconf() == override
    assert get_urlconf() == current