Python werkzeug.routing.NotFound() Examples

The following are 16 code examples of werkzeug.routing.NotFound(). 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 werkzeug.routing , or try the search function .
Example #1
Source File: app.py    From daenerys with Apache License 2.0 6 votes vote down vote up
def dispatch_url(self, url_string):
        url, url_adapter, query_args = self.parse_url(url_string)

        try:
            endpoint, kwargs = url_adapter.match()
        except NotFound:
            raise NotSupported(url_string)
        except RequestRedirect as e:
            new_url = "{0.new_url}?{1}".format(e, url_encode(query_args))
            return self.dispatch_url(new_url)

        try:
            handler = import_string(endpoint)
            request = Request(url=url, args=query_args)
            return handler(request, **kwargs)
        except RequestRedirect as e:
            return self.dispatch_url(e.new_url) 
Example #2
Source File: alias.py    From maple-blog with GNU General Public License v3.0 6 votes vote down vote up
def get_view_function(url, method='GET'):
    adapter = current_app.url_map.bind('localhost')
    try:
        match = adapter.match(url, method=method)
    except RequestRedirect as e:
        # recursively match redirects
        return get_view_function(e.new_url, method)
    except (MethodNotAllowed, NotFound):
        # no match
        return None

    try:
        # return the view function and arguments
        return current_app.view_functions[match[0]], match[1]
    except KeyError:
        # no view is associated with the endpoint
        return None 
Example #3
Source File: routing.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def to_python(self, value):
        try:
            return self.model.objects.get_or_404(id=value)
        except NotFound:
            pass
        try:
            quoted = self.quote(value)
            query = db.Q(slug=value) | db.Q(slug=quoted)
            obj = self.model.objects(query).get()
        except (InvalidQueryError, self.model.DoesNotExist):
            # If the model doesn't have a slug or matching slug doesn't exist.
            if self.has_redirected_slug:
                latest = self.model.slug.latest(value)
                if latest:
                    return LazyRedirect(latest)
            return NotFound()
        else:
            if obj.slug != value:
                return LazyRedirect(quoted)
        return obj 
Example #4
Source File: routing.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def to_python(self, value):
        """
        `value` has slashs in it, that's why we inherit from `PathConverter`.

        E.g.: `commune/13200@latest/`, `departement/13@1860-07-01/` or
        `region/76@2016-01-01/Auvergne-Rhone-Alpes/`.

        Note that the slug is not significative but cannot be omitted.
        """
        if '/' not in value:
            return

        level, code = value.split('/')[:2]  # Ignore optional slug

        geoid = GeoZone.SEPARATOR.join([level, code])
        zone = GeoZone.objects.resolve(geoid)

        if not zone and GeoZone.SEPARATOR not in level:
            # Try implicit default prefix
            level = GeoZone.SEPARATOR.join([self.DEFAULT_PREFIX, level])
            geoid = GeoZone.SEPARATOR.join([level, code])
            zone = GeoZone.objects.resolve(geoid)

        return zone or NotFound() 
Example #5
Source File: routing.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def lazy_raise_or_redirect():
    '''
    Raise exception lazily to ensure request.endpoint is set
    Also perform redirect if needed
    '''
    if not request.view_args:
        return
    for name, value in request.view_args.items():
        if isinstance(value, NotFound):
            request.routing_exception = value
            break
        elif isinstance(value, LazyRedirect):
            new_args = request.view_args
            new_args[name] = value.arg
            new_url = url_for(request.endpoint, **new_args)
            return redirect(new_url) 
Example #6
Source File: routing.py    From Flask with Apache License 2.0 6 votes vote down vote up
def test_dispatch(self):
        env = create_environ('/')
        map = r.Map([
            r.Rule('/', endpoint='root'),
            r.Rule('/foo/', endpoint='foo')
        ])
        adapter = map.bind_to_environ(env)

        raise_this = None
        def view_func(endpoint, values):
            if raise_this is not None:
                raise raise_this
            return Response(repr((endpoint, values)))
        dispatch = lambda p, q=False: Response.force_type(adapter.dispatch(view_func, p,
                                                          catch_http_exceptions=q), env)

        assert dispatch('/').data == b"('root', {})"
        assert dispatch('/foo').status_code == 301
        raise_this = r.NotFound()
        self.assert_raises(r.NotFound, lambda: dispatch('/bar'))
        assert dispatch('/bar', True).status_code == 404 
Example #7
Source File: routing.py    From Flask with Apache License 2.0 6 votes vote down vote up
def test_server_name_casing(self):
        m = r.Map([
            r.Rule('/', endpoint='index', subdomain='foo')
        ])

        env = create_environ()
        env['SERVER_NAME'] = env['HTTP_HOST'] = 'FOO.EXAMPLE.COM'
        a = m.bind_to_environ(env, server_name='example.com')
        assert a.match('/') == ('index', {})

        env = create_environ()
        env['SERVER_NAME'] = '127.0.0.1'
        env['SERVER_PORT'] = '5000'
        del env['HTTP_HOST']
        a = m.bind_to_environ(env, server_name='example.com')
        try:
            a.match()
        except r.NotFound:
            pass
        else:
            assert False, 'Expected not found exception' 
Example #8
Source File: routing.py    From Flask with Apache License 2.0 6 votes vote down vote up
def test_dispatch(self):
        env = create_environ('/')
        map = r.Map([
            r.Rule('/', endpoint='root'),
            r.Rule('/foo/', endpoint='foo')
        ])
        adapter = map.bind_to_environ(env)

        raise_this = None
        def view_func(endpoint, values):
            if raise_this is not None:
                raise raise_this
            return Response(repr((endpoint, values)))
        dispatch = lambda p, q=False: Response.force_type(adapter.dispatch(view_func, p,
                                                          catch_http_exceptions=q), env)

        assert dispatch('/').data == b"('root', {})"
        assert dispatch('/foo').status_code == 301
        raise_this = r.NotFound()
        self.assert_raises(r.NotFound, lambda: dispatch('/bar'))
        assert dispatch('/bar', True).status_code == 404 
Example #9
Source File: routing.py    From Flask with Apache License 2.0 6 votes vote down vote up
def test_server_name_casing(self):
        m = r.Map([
            r.Rule('/', endpoint='index', subdomain='foo')
        ])

        env = create_environ()
        env['SERVER_NAME'] = env['HTTP_HOST'] = 'FOO.EXAMPLE.COM'
        a = m.bind_to_environ(env, server_name='example.com')
        assert a.match('/') == ('index', {})

        env = create_environ()
        env['SERVER_NAME'] = '127.0.0.1'
        env['SERVER_PORT'] = '5000'
        del env['HTTP_HOST']
        a = m.bind_to_environ(env, server_name='example.com')
        try:
            a.match()
        except r.NotFound:
            pass
        else:
            assert False, 'Expected not found exception' 
Example #10
Source File: routing.py    From udata with GNU Affero General Public License v3.0 5 votes vote down vote up
def to_python(self, value):
        try:
            return value if isinstance(value, UUID) else UUID(value.strip())
        except ValueError:
            return NotFound() 
Example #11
Source File: _routing.py    From flask-jwt-router with GNU General Public License v3.0 5 votes vote down vote up
def _does_route_exist(self, url: str, method: str) -> bool:
        adapter = self.app.url_map.bind('')
        try:
            adapter.match(url, method=method)
        except RequestRedirect as e:
            # recursively match redirects
            return self._does_route_exist(e.new_url, method)
        except (MethodNotAllowed, NotFound):
            # no match
            return False
        return True 
Example #12
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_environ_defaults(self):
        environ = create_environ("/foo")
        self.assert_strict_equal(environ["PATH_INFO"], '/foo')
        m = r.Map([r.Rule("/foo", endpoint="foo"), r.Rule("/bar", endpoint="bar")])
        a = m.bind_to_environ(environ)
        self.assert_strict_equal(a.match("/foo"), ('foo', {}))
        self.assert_strict_equal(a.match(), ('foo', {}))
        self.assert_strict_equal(a.match("/bar"), ('bar', {}))
        self.assert_raises(r.NotFound, a.match, "/bars") 
Example #13
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_environ_nonascii_pathinfo(self):
        environ = create_environ(u'/лошадь')
        m = r.Map([
            r.Rule(u'/', endpoint='index'),
            r.Rule(u'/лошадь', endpoint='horse')
        ])
        a = m.bind_to_environ(environ)
        self.assert_strict_equal(a.match(u'/'), ('index', {}))
        self.assert_strict_equal(a.match(u'/лошадь'), ('horse', {}))
        self.assert_raises(r.NotFound, a.match, u'/барсук') 
Example #14
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_environ_defaults(self):
        environ = create_environ("/foo")
        self.assert_strict_equal(environ["PATH_INFO"], '/foo')
        m = r.Map([r.Rule("/foo", endpoint="foo"), r.Rule("/bar", endpoint="bar")])
        a = m.bind_to_environ(environ)
        self.assert_strict_equal(a.match("/foo"), ('foo', {}))
        self.assert_strict_equal(a.match(), ('foo', {}))
        self.assert_strict_equal(a.match("/bar"), ('bar', {}))
        self.assert_raises(r.NotFound, a.match, "/bars") 
Example #15
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_environ_nonascii_pathinfo(self):
        environ = create_environ(u'/лошадь')
        m = r.Map([
            r.Rule(u'/', endpoint='index'),
            r.Rule(u'/лошадь', endpoint='horse')
        ])
        a = m.bind_to_environ(environ)
        self.assert_strict_equal(a.match(u'/'), ('index', {}))
        self.assert_strict_equal(a.match(u'/лошадь'), ('horse', {}))
        self.assert_raises(r.NotFound, a.match, u'/барсук') 
Example #16
Source File: routing.py    From Flask with Apache License 2.0 4 votes vote down vote up
def test_basic_routing(self):
        map = r.Map([
            r.Rule('/', endpoint='index'),
            r.Rule('/foo', endpoint='foo'),
            r.Rule('/bar/', endpoint='bar')
        ])
        adapter = map.bind('example.org', '/')
        assert adapter.match('/') == ('index', {})
        assert adapter.match('/foo') == ('foo', {})
        assert adapter.match('/bar/') == ('bar', {})
        self.assert_raises(r.RequestRedirect, lambda: adapter.match('/bar'))
        self.assert_raises(r.NotFound, lambda: adapter.match('/blub'))

        adapter = map.bind('example.org', '/test')
        try:
            adapter.match('/bar')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://example.org/test/bar/'
        else:
            self.fail('Expected request redirect')

        adapter = map.bind('example.org', '/')
        try:
            adapter.match('/bar')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://example.org/bar/'
        else:
            self.fail('Expected request redirect')

        adapter = map.bind('example.org', '/')
        try:
            adapter.match('/bar', query_args={'aha': 'muhaha'})
        except r.RequestRedirect as e:
            assert e.new_url == 'http://example.org/bar/?aha=muhaha'
        else:
            self.fail('Expected request redirect')

        adapter = map.bind('example.org', '/')
        try:
            adapter.match('/bar', query_args='aha=muhaha')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://example.org/bar/?aha=muhaha'
        else:
            self.fail('Expected request redirect')

        adapter = map.bind_to_environ(create_environ('/bar?foo=bar',
                                                     'http://example.org/'))
        try:
            adapter.match()
        except r.RequestRedirect as e:
            assert e.new_url == 'http://example.org/bar/?foo=bar'
        else:
            self.fail('Expected request redirect')