Python werkzeug.routing 模块,Map() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用werkzeug.routing.Map()

项目:deb-python-falcon    作者:openstack    | 项目源码 | 文件源码
def werkzeug(body, headers):
    import werkzeug.wrappers as werkzeug
    from werkzeug.routing import Map, Rule

    path = '/hello/<account_id>/test'
    url_map = Map([Rule(path, endpoint='hello')])

    @werkzeug.Request.application
    def hello(request):
        user_agent = request.headers['User-Agent']  # NOQA
        limit = request.args.get('limit', '10')  # NOQA
        adapter = url_map.bind_to_environ(request.environ)  # NOQA
        endpoint, values = adapter.match()  # NOQA
        aid = values['account_id']  # NOQA

        return werkzeug.Response(body, headers=headers,
                                 mimetype='text/plain')

    return hello
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_http_host_before_server_name(self):
        env = {
            'HTTP_HOST':            'wiki.example.com',
            'SERVER_NAME':          'web0.example.com',
            'SERVER_PORT':          '80',
            'SCRIPT_NAME':          '',
            'PATH_INFO':            '',
            'REQUEST_METHOD':       'GET',
            'wsgi.url_scheme':      'http'
        }
        map = r.Map([r.Rule('/', endpoint='index', subdomain='wiki')])
        adapter = map.bind_to_environ(env, server_name='example.com')
        assert adapter.match('/') == ('index', {})
        assert adapter.build('index', force_external=True) == 'http://wiki.example.com/'
        assert adapter.build('index') == '/'

        env['HTTP_HOST'] = 'admin.example.com'
        adapter = map.bind_to_environ(env, server_name='example.com')
        assert adapter.build('index') == 'http://wiki.example.com/'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_server_name_interpolation(self):
        server_name = 'example.invalid'
        map = r.Map([r.Rule('/', endpoint='index'),
                     r.Rule('/', endpoint='alt', subdomain='alt')])

        env = create_environ('/', 'http://%s/' % server_name)
        adapter = map.bind_to_environ(env, server_name=server_name)
        assert adapter.match() == ('index', {})

        env = create_environ('/', 'http://alt.%s/' % server_name)
        adapter = map.bind_to_environ(env, server_name=server_name)
        assert adapter.match() == ('alt', {})

        env = create_environ('/', 'http://%s/' % server_name)
        adapter = map.bind_to_environ(env, server_name='foo')
        assert adapter.subdomain == '<invalid>'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_method_fallback(self):
        map = r.Map([
            r.Rule('/', endpoint='index', methods=['GET']),
            r.Rule('/<name>', endpoint='hello_name', methods=['GET']),
            r.Rule('/select', endpoint='hello_select', methods=['POST']),
            r.Rule('/search_get', endpoint='search', methods=['GET']),
            r.Rule('/search_post', endpoint='search', methods=['POST'])
        ])
        adapter = map.bind('example.com')
        assert adapter.build('index') == '/'
        assert adapter.build('index', method='GET') == '/'
        assert adapter.build('hello_name', {'name': 'foo'}) == '/foo'
        assert adapter.build('hello_select') == '/select'
        assert adapter.build('hello_select', method='POST') == '/select'
        assert adapter.build('search') == '/search_get'
        assert adapter.build('search', method='GET') == '/search_get'
        assert adapter.build('search', method='POST') == '/search_post'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_double_defaults(self):
        for prefix in '', '/aaa':
            m = r.Map([
                r.Rule(prefix + '/', defaults={'foo': 1, 'bar': False}, endpoint='x'),
                r.Rule(prefix + '/<int:foo>', defaults={'bar': False}, endpoint='x'),
                r.Rule(prefix + '/bar/', defaults={'foo': 1, 'bar': True}, endpoint='x'),
                r.Rule(prefix + '/bar/<int:foo>', defaults={'bar': True}, endpoint='x')
            ])
            a = m.bind('example.com')

            assert a.match(prefix + '/') == ('x', {'foo': 1, 'bar': False})
            assert a.match(prefix + '/2') == ('x', {'foo': 2, 'bar': False})
            assert a.match(prefix + '/bar/') == ('x', {'foo': 1, 'bar': True})
            assert a.match(prefix + '/bar/2') == ('x', {'foo': 2, 'bar': True})

            assert a.build('x', {'foo': 1, 'bar': False}) == prefix + '/'
            assert a.build('x', {'foo': 2, 'bar': False}) == prefix + '/2'
            assert a.build('x', {'bar': False}) == prefix + '/'
            assert a.build('x', {'foo': 1, 'bar': True}) == prefix + '/bar/'
            assert a.build('x', {'foo': 2, 'bar': True}) == prefix + '/bar/2'
            assert a.build('x', {'bar': True}) == prefix + '/bar/'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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'
项目:Flask    作者:Humbertzhang    | 项目源码 | 文件源码
def __init__(self):
        #??{ rule: endpoint + ':' + methods }???
        #rule???????URL??? <string:name> ?<int:id>
        #????????????
        self.url_map = Map()

        #??endpointname: method list???
        self.view_functions = {}

        #request stack
        self.requests_stack = LocalStack()


        #a handler for 
        self.error_handlers = {}
        make_default_error_handlers(self.error_handlers)
项目:dorky    作者:recordedfuture    | 项目源码 | 文件源码
def __init__(self):
        template_path = os.path.join(os.path.dirname(__file__), 'mgmt_ui', 'templates')
        self.jinja_env = Environment(loader=FileSystemLoader(template_path),
                                     autoescape=True)

        get_hostname = lambda url: urlparse.urlparse(url).netloc
        self.jinja_env.filters['hostname'] = get_hostname

        self.url_map = Map([
            Rule('/', endpoint='main'),
            Rule('/disable', endpoint='disable'),
            Rule('/get', endpoint='get'),
            Rule('/update', endpoint='update'),
            Rule('/delete', endpoint='delete'),
            Rule('/edit_blacklist', endpoint='edit_blacklist')
        ])
        cfg = ConfigParser.ConfigParser()
        cfg.read('dorking.cfg')

        self.storage = DorkDB(cfg)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def werkzeug(body, headers):
    import werkzeug.wrappers as werkzeug
    from werkzeug.routing import Map, Rule

    path = '/hello/<account_id>/test'
    url_map = Map([Rule(path, endpoint='hello')])

    @werkzeug.Request.application
    def hello(request):
        user_agent = request.headers['User-Agent']  # NOQA
        limit = request.args.get('limit', '10')  # NOQA
        adapter = url_map.bind_to_environ(request.environ)  # NOQA
        endpoint, values = adapter.match()  # NOQA
        aid = values['account_id']  # NOQA

        return werkzeug.Response(body, headers=headers,
                                 mimetype='text/plain')

    return hello
项目:coroutx    作者:neo1218    | 项目源码 | 文件源码
def __init__(self, package_name):
        self.debug = False
        self.package_name = package_name
        self.view_functions = {}
        self.error_handlers = {}
        self.request_init_funcs = []
        self.request_shutdown_funcs = []
        self.url_map = Map()

        if self.static_path is not None:
            self.url_map.add(Rule(self.static_path + '/<filename>',
                                  build_only=True, endpoint='static'))

        self.jinja_env = Environment(loader=self.create_jinja_loader(),
                                     **self.jinja_options)
        self.jinja_env.globals.update(
            url_for=url_for,
            request=request,
            session=session,
            g=g,
            get_flashed_messages=get_flashed_messages
        )
项目:tuning-box    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        super(TestLevels, self).setUp()
        self.map = routing.Map([
            routing.Rule('/smth/<levels:levels>values', endpoint='l'),
        ], converters={'levels': converters.Levels})
        self.mapad = self.map.bind('example.org', '/')
项目:tuning-box    作者:openstack    | 项目源码 | 文件源码
def setUp(self):
        super(TestIdOrName, self).setUp()
        self.map = routing.Map([
            routing.Rule('/<id_or_name:id_or_name>', endpoint='i'),
        ], converters={'id_or_name': converters.IdOrName})
        self.mapad = self.map.bind('example.org', '/')
项目:core-python    作者:yidao620c    | 项目源码 | 文件源码
def __init__(self, config):
        self.redis = redis.Redis(config['redis_host'], config['redis_port'])
        template_path = os.path.join(os.path.dirname(__file__), 'templates')
        self.jinja_env = Environment(loader=FileSystemLoader(template_path),
                                     autoescape=True)
        self.url_map = Map([
            Rule('/', endpoint='new_url'),
            Rule('/<short_id>', endpoint='follow_short_link'),
            Rule('/<short_id>+', endpoint='short_link_details')
        ])
项目:pixie    作者:algorithm-ninja    | 项目源码 | 文件源码
def __init__(self, contestant_ip_format, worker_ip_format, reboot_delay, ethers_manager):
        self.contestant_ip_format = contestant_ip_format
        self.worker_ip_format = worker_ip_format
        self.reboot_delay = reboot_delay
        self.ethers_manager = ethers_manager
        self.reboot_string = 0

        gevent.spawn(self.reboot_loop)

        self.router = Map([
            Rule('/contestant', methods=['GET'], endpoint='contestant'),
            Rule('/worker', methods=['GET'], endpoint='worker'),
            Rule('/reboot_timestamp', methods=['GET'], endpoint='reboot_timestamp')
        ])
项目:pixie    作者:algorithm-ninja    | 项目源码 | 文件源码
def __init__(self, configs, collector_prefix):
        self.configs = []
        self.default_config = dict()
        self.default_config['image_method'] = IMAGE_METHOD
        self.default_config['collector_prefix'] = collector_prefix
        for config in configs:
            self.configs.append(self.load_config(config))
        self.router = Map([
            Rule('/', methods=['GET'], endpoint='default'),
            Rule('/wipe', methods=['GET'], endpoint='wipe')
        ])
项目:Flask-SocketAPI    作者:kyouko-taiga    | 项目源码 | 文件源码
def __init__(self, socketio=None, namespace=None):
        self.namespace = namespace

        self.routes = Map()
        self.urls = self.routes.bind('/', '/')

        self.patch_handlers = {}

        if socketio is not None:
            self.init_socketio(socketio)
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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")
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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'/??????')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_basic_building(self):
        map = r.Map([
            r.Rule('/', endpoint='index'),
            r.Rule('/foo', endpoint='foo'),
            r.Rule('/bar/<baz>', endpoint='bar'),
            r.Rule('/bar/<int:bazi>', endpoint='bari'),
            r.Rule('/bar/<float:bazf>', endpoint='barf'),
            r.Rule('/bar/<path:bazp>', endpoint='barp'),
            r.Rule('/hehe', endpoint='blah', subdomain='blah')
        ])
        adapter = map.bind('example.org', '/', subdomain='blah')

        assert adapter.build('index', {}) == 'http://example.org/'
        assert adapter.build('foo', {}) == 'http://example.org/foo'
        assert adapter.build('bar', {'baz': 'blub'}) == 'http://example.org/bar/blub'
        assert adapter.build('bari', {'bazi': 50}) == 'http://example.org/bar/50'
        assert adapter.build('barf', {'bazf': 0.815}) == 'http://example.org/bar/0.815'
        assert adapter.build('barp', {'bazp': 'la/di'}) == 'http://example.org/bar/la/di'
        assert adapter.build('blah', {}) == '/hehe'
        self.assert_raises(r.BuildError, lambda: adapter.build('urks'))

        adapter = map.bind('example.org', '/test', subdomain='blah')
        assert adapter.build('index', {}) == 'http://example.org/test/'
        assert adapter.build('foo', {}) == 'http://example.org/test/foo'
        assert adapter.build('bar', {'baz': 'blub'}) == 'http://example.org/test/bar/blub'
        assert adapter.build('bari', {'bazi': 50}) == 'http://example.org/test/bar/50'
        assert adapter.build('barf', {'bazf': 0.815}) == 'http://example.org/test/bar/0.815'
        assert adapter.build('barp', {'bazp': 'la/di'}) == 'http://example.org/test/bar/la/di'
        assert adapter.build('blah', {}) == '/test/hehe'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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'})
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_adapter_url_parameter_sorting(self):
        map = r.Map([r.Rule('/', endpoint='index')], sort_parameters=True,
                     sort_key=lambda x: x[1])
        adapter = map.bind('localhost', '/')
        assert adapter.build('index', {'x': 20, 'y': 10, 'z': 30},
            force_external=True) == 'http://localhost/?y=10&x=20&z=30'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_adapter_match_return_rule(self):
        rule = r.Rule('/foo/', endpoint='foo')
        map = r.Map([rule])
        adapter = map.bind('localhost', '/')
        assert adapter.match('/foo/', return_rule=True) == (rule, {})
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_non_string_parts(self):
        m = r.Map([
            r.Rule('/<foo>', endpoint='foo')
        ])
        a = m.bind('example.com')
        self.assert_equal(a.build('foo', {'foo': 42}), '/42')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_default_converters(self):
        class MyMap(r.Map):
            default_converters = r.Map.default_converters.copy()
            default_converters['foo'] = r.UnicodeConverter
        assert isinstance(r.Map.default_converters, ImmutableDict)
        m = MyMap([
            r.Rule('/a/<foo:a>', endpoint='a'),
            r.Rule('/b/<foo:b>', endpoint='b'),
            r.Rule('/c/<c>', endpoint='c')
        ], converters={'bar': r.UnicodeConverter})
        a = m.bind('example.org', '/')
        assert a.match('/a/1') == ('a', {'a': '1'})
        assert a.match('/b/2') == ('b', {'b': '2'})
        assert a.match('/c/3') == ('c', {'c': '3'})
        assert 'foo' not in r.Map.default_converters
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_build_append_unknown(self):
        map = r.Map([
            r.Rule('/bar/<float:bazf>', endpoint='barf')
        ])
        adapter = map.bind('example.org', '/', subdomain='blah')
        assert adapter.build('barf', {'bazf': 0.815, 'bif' : 1.0}) == \
            'http://example.org/bar/0.815?bif=1.0'
        assert adapter.build('barf', {'bazf': 0.815, 'bif' : 1.0},
            append_unknown=False) == 'http://example.org/bar/0.815'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_implicit_head(self):
        url_map = r.Map([
            r.Rule('/get', methods=['GET'], endpoint='a'),
            r.Rule('/post', methods=['POST'], endpoint='b')
        ])
        adapter = url_map.bind('example.org')
        assert adapter.match('/get', method='HEAD') == ('a', {})
        self.assert_raises(r.MethodNotAllowed, adapter.match,
                           '/post', method='HEAD')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_protocol_joining_bug(self):
        m = r.Map([r.Rule('/<foo>', endpoint='x')])
        a = m.bind('example.org')
        assert a.build('x', {'foo': 'x:y'}) == '/x:y'
        assert a.build('x', {'foo': 'x:y'}, force_external=True) == \
            'http://example.org/x:y'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_external_building_with_port(self):
        map = r.Map([
            r.Rule('/', endpoint='index'),
        ])
        adapter = map.bind('example.org:5000', '/')
        built_url = adapter.build('index', {}, force_external=True)
        assert built_url == 'http://example.org:5000/', built_url
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_external_building_with_port_bind_to_environ(self):
        map = r.Map([
            r.Rule('/', endpoint='index'),
        ])
        adapter = map.bind_to_environ(
            create_environ('/', 'http://example.org:5000/'),
            server_name="example.org:5000"
        )
        built_url = adapter.build('index', {}, force_external=True)
        assert built_url == 'http://example.org:5000/', built_url
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_external_building_with_port_bind_to_environ_wrong_servername(self):
        map = r.Map([
            r.Rule('/', endpoint='index'),
        ])
        environ = create_environ('/', 'http://example.org:5000/')
        adapter = map.bind_to_environ(environ, server_name="example.org")
        assert adapter.subdomain == '<invalid>'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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'
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_unicode_rules(self):
        m = r.Map([
            r.Rule(u'/?????/', endpoint='enter'),
            r.Rule(u'/foo+bar/', endpoint='foobar')
        ])
        a = m.bind(u'?.example.com')
        try:
            a.match(u'/?????')
        except r.RequestRedirect as e:
            self.assert_strict_equal(e.new_url, 'http://xn--n3h.example.com/'
                              '%D0%B2%D0%BE%D0%B9%D1%82%D0%B8/')
        endpoint, values = a.match(u'/?????/')
        self.assert_strict_equal(endpoint, 'enter')
        self.assert_strict_equal(values, {})

        try:
            a.match(u'/foo+bar')
        except r.RequestRedirect as e:
            self.assert_strict_equal(e.new_url, 'http://xn--n3h.example.com/'
                              'foo+bar/')
        endpoint, values = a.match(u'/foo+bar/')
        self.assert_strict_equal(endpoint, 'foobar')
        self.assert_strict_equal(values, {})

        url = a.build('enter', {}, force_external=True)
        self.assert_strict_equal(url, 'http://xn--n3h.example.com/%D0%B2%D0%BE%D0%B9%D1%82%D0%B8/')

        url = a.build('foobar', {}, force_external=True)
        self.assert_strict_equal(url, 'http://xn--n3h.example.com/foo+bar/')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_map_repr(self):
        m = r.Map([
            r.Rule(u'/wat', endpoint='enter'),
            r.Rule(u'/woop', endpoint='foobar')
        ])
        rv = repr(m)
        self.assert_strict_equal(rv,
            "Map([<Rule '/woop' -> foobar>, <Rule '/wat' -> enter>])")
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_reverse_slash_behavior(self):
        class MyRequest(wrappers.ReverseSlashBehaviorRequestMixin, Request):
            pass
        req = MyRequest.from_values('/foo/bar', 'http://example.com/test')
        assert req.url == 'http://example.com/test/foo/bar'
        assert req.path == 'foo/bar'
        assert req.script_root == '/test/'

        # make sure the routing system works with the slashes in
        # reverse order as well.
        map = routing.Map([routing.Rule('/foo/bar', endpoint='foo')])
        adapter = map.bind_to_environ(req.environ)
        assert adapter.match() == ('foo', {})
        adapter = map.bind(req.host, req.script_root)
        assert adapter.match(req.path) == ('foo', {})
项目:holla    作者:NKUCodingCat    | 项目源码 | 文件源码
def __init__(self):
        self.Response = Response  # Just an alias of Response Class
        self.url_map = Map([])
        pass
项目:daenerys    作者:dongweiming    | 项目源码 | 文件源码
def __init__(self, ignore_sites=set()):
        self.url_map = Map(strict_slashes=False, host_matching=True,
                           redirect_defaults=False)
        self.ignore_sites = ignore_sites
项目:territoriali-backend    作者:algorithm-ninja    | 项目源码 | 文件源码
def __init__(self):
        self.handlers = {
            "contest": ContestHandler(),
            "info": InfoHandler(),
            "upload": UploadHandler(),
            "admin": AdminHandler()
        }

        # The router tries to match the rules, the endpoint MUST be a string with this format
        #     CONTROLLER#ACTION
        # Where CONTROLLER is an handler registered in self.handlers and ACTION is a valid
        # method of that handler
        self.router = Map([
            Rule("/contest", methods=["GET"], endpoint="info#get_contest"),
            Rule("/input/<input_id>", methods=["GET"], endpoint="info#get_input"),
            Rule("/output/<output_id>", methods=["GET"], endpoint="info#get_output"),
            Rule("/source/<source_id>", methods=["GET"], endpoint="info#get_source"),
            Rule("/submission/<submission_id>", methods=["GET"], endpoint="info#get_submission"),
            Rule("/user/<token>", methods=["GET"], endpoint="info#get_user"),
            Rule("/user/<token>/submissions/<task>", methods=["GET"], endpoint="info#get_submissions"),
            Rule("/generate_input", methods=["POST"], endpoint="contest#generate_input"),
            Rule("/submit", methods=["POST"], endpoint="contest#submit"),
            Rule("/upload_source", methods=["POST"], endpoint="upload#upload_source"),
            Rule("/upload_output", methods=["POST"], endpoint="upload#upload_output"),

            Rule("/admin/extract", methods=["POST"], endpoint="admin#extract"),
            Rule("/admin/drop_contest", methods=["POST"], endpoint="admin#drop_contest"),
            Rule("/admin/log", methods=["POST"], endpoint="admin#log"),
            Rule("/admin/start", methods=["POST"], endpoint="admin#start"),
            Rule("/admin/set_extra_time", methods=["POST"], endpoint="admin#set_extra_time"),
            Rule("/admin/status", methods=["POST"], endpoint="admin#status"),
            Rule("/admin/user_list", methods=["POST"], endpoint="admin#user_list")
        ])
项目:Charming_Python    作者:wanzifa    | 项目源码 | 文件源码
def __init__(self, config):
        self.redis = redis.Redis(config['redis_host'], config['redis_port'])  
        template_path = os.path.join(os.path.dirname(__file__), 'templates')
        #autoescape=True??????xml/html???
        self.jinja_env = Environment(loader=FileSystemLoader(template_path),
                                     autoescape=True)
        #Map???????????????????url??????????“??”
        #??????????????????
        self.url_map = Map([
            #Rule????????????????
            Rule('/', endpoint='new_url'),
            Rule('/<short_id>', endpoint='follow_short_link'),
            Rule('/<short_id>+', endpoint='short_link_details')
        ])
项目:flango    作者:theY4Kman    | 项目源码 | 文件源码
def __init__(self, import_name):
        self.import_name = import_name

        self.url_map = Map()
        self.view_functions = {}
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def __init__(self):
        self._url_map = Map()
        self._endpoints = {}
        self._error_handlers = []
        self._instance = None
项目:SP-MOTDPlayer2    作者:KirillMysnik    | 项目源码 | 文件源码
def __init__(self, app=None):
        self.url_map = Map()
        self.handlers = dict()
        if app is not None:
            self.init_app(app)
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
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')
项目:oa_qian    作者:sunqb    | 项目源码 | 文件源码
def test_rule_templates(self):
        testcase = r.RuleTemplate(
            [ r.Submount('/test/$app',
              [ r.Rule('/foo/', endpoint='handle_foo')
              , r.Rule('/bar/', endpoint='handle_bar')
              , r.Rule('/baz/', endpoint='handle_baz')
              ]),
              r.EndpointPrefix('${app}',
              [ r.Rule('/${app}-blah', endpoint='bar')
              , r.Rule('/${app}-meh', endpoint='baz')
              ]),
              r.Subdomain('$app',
              [ r.Rule('/blah', endpoint='x_bar')
              , r.Rule('/meh', endpoint='x_baz')
              ])
            ])

        url_map = r.Map(
            [ testcase(app='test1')
            , testcase(app='test2')
            , testcase(app='test3')
            , testcase(app='test4')
            ])

        out = sorted([(x.rule, x.subdomain, x.endpoint)
                      for x in url_map.iter_rules()])

        assert out == ([
            ('/blah', 'test1', 'x_bar'),
            ('/blah', 'test2', 'x_bar'),
            ('/blah', 'test3', 'x_bar'),
            ('/blah', 'test4', 'x_bar'),
            ('/meh', 'test1', 'x_baz'),
            ('/meh', 'test2', 'x_baz'),
            ('/meh', 'test3', 'x_baz'),
            ('/meh', 'test4', 'x_baz'),
            ('/test/test1/bar/', '', 'handle_bar'),
            ('/test/test1/baz/', '', 'handle_baz'),
            ('/test/test1/foo/', '', 'handle_foo'),
            ('/test/test2/bar/', '', 'handle_bar'),
            ('/test/test2/baz/', '', 'handle_baz'),
            ('/test/test2/foo/', '', 'handle_foo'),
            ('/test/test3/bar/', '', 'handle_bar'),
            ('/test/test3/baz/', '', 'handle_baz'),
            ('/test/test3/foo/', '', 'handle_foo'),
            ('/test/test4/bar/', '', 'handle_bar'),
            ('/test/test4/baz/', '', 'handle_baz'),
            ('/test/test4/foo/', '', 'handle_foo'),
            ('/test1-blah', '', 'test1bar'),
            ('/test1-meh', '', 'test1baz'),
            ('/test2-blah', '', 'test2bar'),
            ('/test2-meh', '', 'test2baz'),
            ('/test3-blah', '', 'test3bar'),
            ('/test3-meh', '', 'test3baz'),
            ('/test4-blah', '', 'test4bar'),
            ('/test4-meh', '', 'test4baz')
        ])
项目:revocation-tracker    作者:alex    | 项目源码 | 文件源码
def __init__(self, cert_db, crtsh_checker):
        self.cert_db = cert_db
        self.crtsh_checker = crtsh_checker

        self.jinja_env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(
                str(Path(__file__).parent.joinpath("templates"))
            ),
            autoescape=True
        )

        self.url_map = routing.Map([
            routing.Rule("/", methods=["GET"], endpoint=self.home),
            routing.Rule(
                "/add-certificate/",
                methods=["POST"],
                endpoint=self.add_certificate
            ),
            routing.Rule(
                "/create-batch/",
                methods=["GET", "POST"],
                endpoint=self.create_batch,
            ),
            routing.Rule(
                "/batches/",
                methods=["GET"],
                endpoint=self.list_batches,
            ),
            routing.Rule(
                "/batch/<batch_id>/",
                methods=["GET"],
                endpoint=self.batch,
            ),
            routing.Rule(
                "/cablint/",
                methods=["GET"],
                endpoint=self.cablint,
            ),
            routing.Rule(
                "/zlint/",
                methods=["GET"],
                endpoint=self.zlint,
            ),
        ])