Python django.urls.get_resolver() Examples

The following are 12 code examples of django.urls.get_resolver(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.urls , or try the search function .
Example #1
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handle_uncaught_exception_notes_serialization_failure(self):
        handler = views.WebApplicationHandler()
        request = make_request()
        request.path = factory.make_name("path")
        failure = self.capture_serialization_failure()
        response = handler.handle_uncaught_exception(
            request=request,
            resolver=get_resolver(None),
            exc_info=failure,
            reraise=False,
        )
        # HTTP 409 is returned...
        self.expectThat(response.status_code, Equals(http.client.CONFLICT))
        # ... and the response is recorded as needing a retry.
        self.expectThat(
            handler._WebApplicationHandler__retry, Contains(response)
        ) 
Example #2
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handle_uncaught_exception_does_not_note_other_failure(self):
        handler = views.WebApplicationHandler()
        request = make_request()
        request.path = factory.make_name("path")
        failure_type = factory.make_exception_type()
        failure = failure_type, failure_type(), None
        response = handler.handle_uncaught_exception(
            request=request,
            resolver=get_resolver(None),
            exc_info=failure,
            reraise=False,
        )
        # HTTP 500 is returned...
        self.expectThat(
            response.status_code, Equals(http.client.INTERNAL_SERVER_ERROR)
        )
        # ... but the response is NOT recorded as needing a retry.
        self.expectThat(
            handler._WebApplicationHandler__retry, Not(Contains(response))
        ) 
Example #3
Source File: test_views.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_handle_uncaught_exception_raises_error_on_api_exception(self):
        handler = views.WebApplicationHandler()
        request = make_request()
        request.path = factory.make_name("path")

        # Capture an exc_info tuple with traceback.
        exc_type = MAASAPIException
        exc_msg = factory.make_name("message")
        try:
            raise exc_type(exc_msg)
        except exc_type:
            exc_info = sys.exc_info()

        response = handler.handle_uncaught_exception(
            request=request,
            resolver=get_resolver(None),
            exc_info=exc_info,
            reraise=False,
        )
        self.assertThat(
            response.status_code, Equals(http.client.INTERNAL_SERVER_ERROR)
        ) 
Example #4
Source File: transactions.py    From sentry-python with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def resolve(
        self,
        path,  # type: str
        urlconf=None,  # type: Union[None, Tuple[URLPattern, URLPattern, URLResolver], Tuple[URLPattern]]
    ):
        # type: (...) -> str
        resolver = get_resolver(urlconf)
        match = self._resolve(resolver, path)
        return match or path 
Example #5
Source File: views.py    From PwnAuth with Apache License 2.0 5 votes vote down vote up
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}) 
Example #6
Source File: renderers.py    From product-definition-center with MIT License 5 votes vote down vote up
def get_url(view, detail_or_list):
    from django.urls import get_resolver
    resolver = get_resolver(None)
    viewname = '%s-%s' % (view.basename, detail_or_list)
    url_template, args = resolver.reverse_dict.getlist(viewname)[1][0][0]
    if len(args) == 1 and args[0] == 'composite_field':
        url = url_template % {'composite_field': '{%s}' % get_id_template(view)}
    else:
        url = url_template % {arg: '{%s}' % arg for arg in args}
    return '<a href="/%s">/%s</a>' % (url, url) 
Example #7
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def raises404(request):
    resolver = get_resolver(None)
    resolver.resolve('/not-in-urls') 
Example #8
Source File: views.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def raises404(request):
    resolver = get_resolver(None)
    resolver.resolve('/not-in-urls') 
Example #9
Source File: views.py    From openprescribing with MIT License 5 votes vote down vote up
def _url_template(view_name):
    """Generate a URL template for a given view, to be interpolated by JS in
    the browser.

    >>> _url_template("measure_for_one_ccg")
    '/measure/{measure}/ccg/{entity_code}/'
    """

    resolver = get_resolver()

    # For the example above, `pattern` is "measure/%(measure)s/ccg/%(entity_code)s/"
    pattern = resolver.reverse_dict[view_name][0][0][0]
    return "/" + pattern.replace("%(", "{").replace(")s", "}") 
Example #10
Source File: doc.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def find_api_resources(urlconf=None):
    """Find the API resources defined in `urlconf`.

    :rtype: :class:`set` of :class:`Resource` instances.
    """
    resolver, accumulator = get_resolver(urlconf), set()
    accumulate_api_resources(resolver, accumulator)
    return accumulator 
Example #11
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_resource_uri_template(self):
    """
    URI template processor.
    See http://bitworking.org/projects/URI-Templates/
    """

    def _convert(template, params=[]):
        """URI template converter"""
        paths = template % dict([p, "{%s}" % p] for p in params)
        return "%s%s" % (get_script_prefix(), paths)

    try:
        resource_uri = self.handler.resource_uri()
        components = [None, [], {}]

        for i, value in enumerate(resource_uri):
            components[i] = value
        lookup_view, args, kwargs = components
        try:
            lookup_view = get_callable(lookup_view)
        except (ImportError, ViewDoesNotExist):
            # Emulate can_fail=True from earlier django versions.
            pass

        possibilities = get_resolver(None).reverse_dict.getlist(lookup_view)
        # The monkey patch is right here: we need to cope with 'possibilities'
        # being a list of tuples with 2 or 3 elements.
        for possibility_data in possibilities:
            possibility = possibility_data[0]
            for result, params in possibility:
                if args:
                    if len(args) != len(params):
                        continue
                    return _convert(result, params)
                else:
                    if set(kwargs.keys()) != set(params):
                        continue
                    return _convert(result, params)
    except Exception:
        return None 
Example #12
Source File: check_numbers.py    From openprescribing with MIT License 4 votes vote down vote up
def paths_to_scrape():
    """Yield paths that should be scraped.

    We're interested in a sample of all pages for organisations.  Rather than
    specify pages we're interested in, we ignore pages we're not interested in.
    """

    # Don't scrape URLs beginning with these prefixes.  They are either static
    # pages, admin pages, or are unlikely to change in an interesting way.
    prefixes_to_ignore = [
        "accounts",
        "admin",
        "api",
        "bnf",
        "bookmarks",
        "chemical",
        "dmd",
        "docs",
    ]

    # get_resolver().reverse_dict is a dict that maps view names or view
    # functions to a data structure that describes how requests should be
    # dispatched.
    for k, v in get_resolver().reverse_dict.items():

        # Ignore records where the key is a view function.
        if not isinstance(k, str):
            continue

        name = k
        pattern = v[0][0][0]
        keys = v[0][0][1]

        # Ignore records starting with prefixes we're not interested in.
        if any(pattern.startswith(prefix) for prefix in prefixes_to_ignore):
            continue

        # Ignore any URLs that are not either parameterisable (these static
        # pages or lists of entities) or for All England.
        if "%" not in pattern and "national/england" not in pattern:
            continue

        path = build_path(pattern, keys)
        yield name, path