Python werkzeug.routing.RequestRedirect() Examples

The following are 30 code examples of werkzeug.routing.RequestRedirect(). 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: ctx.py    From quart with MIT License 6 votes vote down vote up
def match_request(self) -> None:
        """Match the request against the adapter.

        Override this method to configure request matching, it should
        set the request url_rule and view_args and optionally a
        routing_exception.
        """
        try:
            (
                self.request_websocket.url_rule,
                self.request_websocket.view_args,
            ) = self.url_adapter.match(
                return_rule=True
            )  # noqa
        except WBadRequest:
            self.request_websocket.routing_exception = BadRequest()
        except WNotFound:
            self.request_websocket.routing_exception = NotFound()
        except WMethodNotAllowed as error:
            new_error = MethodNotAllowed(error.valid_methods)
            self.request_websocket.routing_exception = new_error
        except WRequestRedirect as error:
            new_error = RedirectRequired(error.new_url)  # type: ignore
            self.request_websocket.routing_exception = new_error 
Example #2
Source File: test_error.py    From Flask-Large-Application-Example with MIT License 6 votes vote down vote up
def test_http_exception(self):
        for exception_cls in HTTPException.__subclasses__():
            if exception_cls is RequestRedirect or exception_cls().code == 412:
                continue

            exception_instance = exception_cls()

            self.add_route_raises_exception(
                ExceptionHandlingSpec(
                    Exception, broad_exception_handler, exception_instance
                )
            )

            resp = self.request()

            self.assertEqual(exception_instance.code, resp.status_code)
            self.assertTrue(resp.is_json)
            self.assertDictEqual({"error": exception_instance.description}, resp.json) 
Example #3
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 #4
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 #5
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_defaults(self):
        map = r.Map([
            r.Rule('/foo/', defaults={'page': 1}, endpoint='foo'),
            r.Rule('/foo/<int:page>', endpoint='foo')
        ])
        adapter = map.bind('example.org', '/')

        assert adapter.match('/foo/') == ('foo', {'page': 1})
        self.assert_raises(r.RequestRedirect, lambda: adapter.match('/foo/1'))
        assert adapter.match('/foo/2') == ('foo', {'page': 2})
        assert adapter.build('foo', {}) == '/foo/'
        assert adapter.build('foo', {'page': 1}) == '/foo/'
        assert adapter.build('foo', {'page': 2}) == '/foo/2' 
Example #6
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_defaults(self):
        map = r.Map([
            r.Rule('/foo/', defaults={'page': 1}, endpoint='foo'),
            r.Rule('/foo/<int:page>', endpoint='foo')
        ])
        adapter = map.bind('example.org', '/')

        assert adapter.match('/foo/') == ('foo', {'page': 1})
        self.assert_raises(r.RequestRedirect, lambda: adapter.match('/foo/1'))
        assert adapter.match('/foo/2') == ('foo', {'page': 2})
        assert adapter.build('foo', {}) == '/foo/'
        assert adapter.build('foo', {'page': 1}) == '/foo/'
        assert adapter.build('foo', {'page': 2}) == '/foo/2' 
Example #7
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_path(self):
        map = r.Map([
            r.Rule('/', defaults={'name': 'FrontPage'}, endpoint='page'),
            r.Rule('/Special', endpoint='special'),
            r.Rule('/<int:year>', endpoint='year'),
            r.Rule('/<path:name>', endpoint='page'),
            r.Rule('/<path:name>/edit', endpoint='editpage'),
            r.Rule('/<path:name>/silly/<path:name2>', endpoint='sillypage'),
            r.Rule('/<path:name>/silly/<path:name2>/edit', endpoint='editsillypage'),
            r.Rule('/Talk:<path:name>', endpoint='talk'),
            r.Rule('/User:<username>', endpoint='user'),
            r.Rule('/User:<username>/<path:name>', endpoint='userpage'),
            r.Rule('/Files/<path:file>', endpoint='files'),
        ])
        adapter = map.bind('example.org', '/')

        assert adapter.match('/') == ('page', {'name':'FrontPage'})
        self.assert_raises(r.RequestRedirect, lambda: adapter.match('/FrontPage'))
        assert adapter.match('/Special') == ('special', {})
        assert adapter.match('/2007') == ('year', {'year':2007})
        assert adapter.match('/Some/Page') == ('page', {'name':'Some/Page'})
        assert adapter.match('/Some/Page/edit') == ('editpage', {'name':'Some/Page'})
        assert adapter.match('/Foo/silly/bar') == ('sillypage', {'name':'Foo', 'name2':'bar'})
        assert adapter.match('/Foo/silly/bar/edit') == ('editsillypage', {'name':'Foo', 'name2':'bar'})
        assert adapter.match('/Talk:Foo/Bar') == ('talk', {'name':'Foo/Bar'})
        assert adapter.match('/User:thomas') == ('user', {'username':'thomas'})
        assert adapter.match('/User:thomas/projects/werkzeug') == \
            ('userpage', {'username':'thomas', 'name':'projects/werkzeug'})
        assert adapter.match('/Files/downloads/werkzeug/0.2.zip') == \
            ('files', {'file':'downloads/werkzeug/0.2.zip'}) 
Example #8
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_request_direct_charset_bug(self):
        map = r.Map([r.Rule(u'/öäü/')])
        adapter = map.bind('localhost', '/')
        try:
            adapter.match(u'/öäü')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://localhost/%C3%B6%C3%A4%C3%BC/'
        else:
            self.fail('expected request redirect exception') 
Example #9
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_request_redirect_default_subdomain(self):
        map = r.Map([r.Rule(u'/foo', defaults={'bar': 42}, subdomain='test'),
                     r.Rule(u'/foo/<int:bar>', subdomain='other')])
        adapter = map.bind('localhost', '/', subdomain='other')
        try:
            adapter.match(u'/foo/42')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://test.localhost/foo'
        else:
            self.fail('expected request redirect exception') 
Example #10
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_alias_redirects(self):
        m = r.Map([
            r.Rule('/', endpoint='index'),
            r.Rule('/index.html', endpoint='index', alias=True),
            r.Rule('/users/', defaults={'page': 1}, endpoint='users'),
            r.Rule('/users/index.html', defaults={'page': 1}, alias=True,
                   endpoint='users'),
            r.Rule('/users/page/<int:page>', endpoint='users'),
            r.Rule('/users/page-<int:page>.html', alias=True, endpoint='users'),
        ])
        a = m.bind('example.com')

        def ensure_redirect(path, new_url, args=None):
            try:
                a.match(path, query_args=args)
            except r.RequestRedirect as e:
                assert e.new_url == 'http://example.com' + new_url
            else:
                assert False, 'expected redirect'

        ensure_redirect('/index.html', '/')
        ensure_redirect('/users/index.html', '/users/')
        ensure_redirect('/users/page-2.html', '/users/page/2')
        ensure_redirect('/users/page-1.html', '/users/')
        ensure_redirect('/users/page-1.html', '/users/?foo=bar', {'foo': 'bar'})

        assert a.build('index') == '/'
        assert a.build('users', {'page': 1}) == '/users/'
        assert a.build('users', {'page': 2}) == '/users/page/2' 
Example #11
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_host_matching(self):
        m = r.Map([
            r.Rule('/', endpoint='index', host='www.<domain>'),
            r.Rule('/', endpoint='files', host='files.<domain>'),
            r.Rule('/foo/', defaults={'page': 1}, host='www.<domain>', endpoint='x'),
            r.Rule('/<int:page>', host='files.<domain>', endpoint='x')
        ], host_matching=True)

        a = m.bind('www.example.com')
        assert a.match('/') == ('index', {'domain': 'example.com'})
        assert a.match('/foo/') == ('x', {'domain': 'example.com', 'page': 1})
        try:
            a.match('/foo')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://www.example.com/foo/'
        else:
            assert False, 'expected redirect'

        a = m.bind('files.example.com')
        assert a.match('/') == ('files', {'domain': 'example.com'})
        assert a.match('/2') == ('x', {'domain': 'example.com', 'page': 2})
        try:
            a.match('/1')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://www.example.com/foo/'
        else:
            assert False, 'expected redirect' 
Example #12
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_redirect_request_exception_code(self):
        exc = r.RequestRedirect('http://www.google.com/')
        exc.code = 307
        env = create_environ()
        self.assert_strict_equal(exc.get_response(env).status_code, exc.code) 
Example #13
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_redirect_path_quoting(self):
        url_map = r.Map([
            r.Rule('/<category>', defaults={'page': 1}, endpoint='category'),
            r.Rule('/<category>/page/<int:page>', endpoint='category')
        ])

        adapter = url_map.bind('example.com')
        try:
            adapter.match('/foo bar/page/1')
        except r.RequestRedirect as e:
            response = e.get_response({})
            self.assert_strict_equal(response.headers['location'],
                                     u'http://example.com/foo%20bar')
        else:
            self.fail('Expected redirect') 
Example #14
Source File: app.py    From Flask with Apache License 2.0 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request) 
Example #15
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 #16
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_path(self):
        map = r.Map([
            r.Rule('/', defaults={'name': 'FrontPage'}, endpoint='page'),
            r.Rule('/Special', endpoint='special'),
            r.Rule('/<int:year>', endpoint='year'),
            r.Rule('/<path:name>', endpoint='page'),
            r.Rule('/<path:name>/edit', endpoint='editpage'),
            r.Rule('/<path:name>/silly/<path:name2>', endpoint='sillypage'),
            r.Rule('/<path:name>/silly/<path:name2>/edit', endpoint='editsillypage'),
            r.Rule('/Talk:<path:name>', endpoint='talk'),
            r.Rule('/User:<username>', endpoint='user'),
            r.Rule('/User:<username>/<path:name>', endpoint='userpage'),
            r.Rule('/Files/<path:file>', endpoint='files'),
        ])
        adapter = map.bind('example.org', '/')

        assert adapter.match('/') == ('page', {'name':'FrontPage'})
        self.assert_raises(r.RequestRedirect, lambda: adapter.match('/FrontPage'))
        assert adapter.match('/Special') == ('special', {})
        assert adapter.match('/2007') == ('year', {'year':2007})
        assert adapter.match('/Some/Page') == ('page', {'name':'Some/Page'})
        assert adapter.match('/Some/Page/edit') == ('editpage', {'name':'Some/Page'})
        assert adapter.match('/Foo/silly/bar') == ('sillypage', {'name':'Foo', 'name2':'bar'})
        assert adapter.match('/Foo/silly/bar/edit') == ('editsillypage', {'name':'Foo', 'name2':'bar'})
        assert adapter.match('/Talk:Foo/Bar') == ('talk', {'name':'Foo/Bar'})
        assert adapter.match('/User:thomas') == ('user', {'username':'thomas'})
        assert adapter.match('/User:thomas/projects/werkzeug') == \
            ('userpage', {'username':'thomas', 'name':'projects/werkzeug'})
        assert adapter.match('/Files/downloads/werkzeug/0.2.zip') == \
            ('files', {'file':'downloads/werkzeug/0.2.zip'}) 
Example #17
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_request_direct_charset_bug(self):
        map = r.Map([r.Rule(u'/öäü/')])
        adapter = map.bind('localhost', '/')
        try:
            adapter.match(u'/öäü')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://localhost/%C3%B6%C3%A4%C3%BC/'
        else:
            self.fail('expected request redirect exception') 
Example #18
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_request_redirect_default_subdomain(self):
        map = r.Map([r.Rule(u'/foo', defaults={'bar': 42}, subdomain='test'),
                     r.Rule(u'/foo/<int:bar>', subdomain='other')])
        adapter = map.bind('localhost', '/', subdomain='other')
        try:
            adapter.match(u'/foo/42')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://test.localhost/foo'
        else:
            self.fail('expected request redirect exception') 
Example #19
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_alias_redirects(self):
        m = r.Map([
            r.Rule('/', endpoint='index'),
            r.Rule('/index.html', endpoint='index', alias=True),
            r.Rule('/users/', defaults={'page': 1}, endpoint='users'),
            r.Rule('/users/index.html', defaults={'page': 1}, alias=True,
                   endpoint='users'),
            r.Rule('/users/page/<int:page>', endpoint='users'),
            r.Rule('/users/page-<int:page>.html', alias=True, endpoint='users'),
        ])
        a = m.bind('example.com')

        def ensure_redirect(path, new_url, args=None):
            try:
                a.match(path, query_args=args)
            except r.RequestRedirect as e:
                assert e.new_url == 'http://example.com' + new_url
            else:
                assert False, 'expected redirect'

        ensure_redirect('/index.html', '/')
        ensure_redirect('/users/index.html', '/users/')
        ensure_redirect('/users/page-2.html', '/users/page/2')
        ensure_redirect('/users/page-1.html', '/users/')
        ensure_redirect('/users/page-1.html', '/users/?foo=bar', {'foo': 'bar'})

        assert a.build('index') == '/'
        assert a.build('users', {'page': 1}) == '/users/'
        assert a.build('users', {'page': 2}) == '/users/page/2' 
Example #20
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_host_matching(self):
        m = r.Map([
            r.Rule('/', endpoint='index', host='www.<domain>'),
            r.Rule('/', endpoint='files', host='files.<domain>'),
            r.Rule('/foo/', defaults={'page': 1}, host='www.<domain>', endpoint='x'),
            r.Rule('/<int:page>', host='files.<domain>', endpoint='x')
        ], host_matching=True)

        a = m.bind('www.example.com')
        assert a.match('/') == ('index', {'domain': 'example.com'})
        assert a.match('/foo/') == ('x', {'domain': 'example.com', 'page': 1})
        try:
            a.match('/foo')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://www.example.com/foo/'
        else:
            assert False, 'expected redirect'

        a = m.bind('files.example.com')
        assert a.match('/') == ('files', {'domain': 'example.com'})
        assert a.match('/2') == ('x', {'domain': 'example.com', 'page': 2})
        try:
            a.match('/1')
        except r.RequestRedirect as e:
            assert e.new_url == 'http://www.example.com/foo/'
        else:
            assert False, 'expected redirect' 
Example #21
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_redirect_request_exception_code(self):
        exc = r.RequestRedirect('http://www.google.com/')
        exc.code = 307
        env = create_environ()
        self.assert_strict_equal(exc.get_response(env).status_code, exc.code) 
Example #22
Source File: routing.py    From Flask with Apache License 2.0 5 votes vote down vote up
def test_redirect_path_quoting(self):
        url_map = r.Map([
            r.Rule('/<category>', defaults={'page': 1}, endpoint='category'),
            r.Rule('/<category>/page/<int:page>', endpoint='category')
        ])

        adapter = url_map.bind('example.com')
        try:
            adapter.match('/foo bar/page/1')
        except r.RequestRedirect as e:
            response = e.get_response({})
            self.assert_strict_equal(response.headers['location'],
                                     u'http://example.com/foo%20bar')
        else:
            self.fail('Expected redirect') 
Example #23
Source File: app.py    From syntheticmass with Apache License 2.0 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request) 
Example #24
Source File: app.py    From recruit with Apache License 2.0 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request) 
Example #25
Source File: app.py    From jbox with MIT License 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request) 
Example #26
Source File: app.py    From RSSNewsGAE with Apache License 2.0 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request) 
Example #27
Source File: app.py    From Financial-Portfolio-Flask with MIT License 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request) 
Example #28
Source File: app.py    From Flask-P2P with MIT License 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request) 
Example #29
Source File: app.py    From planespotter with MIT License 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request) 
Example #30
Source File: app.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def raise_routing_exception(self, request):
        """Exceptions that are recording during routing are reraised with
        this method.  During debug we are not reraising redirect requests
        for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
        a different error instead to help debug situations.

        :internal:
        """
        if not self.debug \
           or not isinstance(request.routing_exception, RequestRedirect) \
           or request.method in ('GET', 'HEAD', 'OPTIONS'):
            raise request.routing_exception

        from .debughelpers import FormDataRoutingRedirect
        raise FormDataRoutingRedirect(request)