本文整理汇总了Python中aiohttp.web.UrlDispatcher类的典型用法代码示例。如果您正苦于以下问题:Python UrlDispatcher类的具体用法?Python UrlDispatcher怎么用?Python UrlDispatcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UrlDispatcher类的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: RouteProvider
class RouteProvider():
def __init__(self, application):
self._dispatcher = UrlDispatcher()
self._application = application
def add_url_rule(self, method, path, handler, *, name=None):
name = name or pythonify_name(handler.__name__)
self._dispatcher.add_route(method, path, handler, name=name)
def add_with_decorator(self, path, *, method="GET", name=None):
def _wrapper(fn):
self.add_url_rule(method, path, fn, name=name)
return fn
return _wrapper
@asyncio.coroutine
def resolve(self, request):
"""
根据请求里面的 method 和 path 找到对应的 match dict
"""
return (yield from self._dispatcher.resolve(request))
def url(self, name, **kwargs):
assert name in self._dispatcher
return self._dispatcher[name].url(**kwargs)
示例2: ParentResource
class ParentResource(Resource):
def __init__(self, path, *, name=None):
super(ParentResource, self).__init__(name=name)
self._path = path.rstrip('/')
self.router = UrlDispatcher()
@asyncio.coroutine
def resolve(self, method, path):
allowed_methods = set()
if not path.startswith(self._path + '/'):
return None, allowed_methods
path = path[len(self._path):]
for resource in self.router._resources:
match_dict, allowed = yield from resource.resolve(method, path)
if match_dict is not None:
return match_dict, allowed_methods
else:
allowed_methods |= allowed
return None, allowed_methods
def add_resource(self, path, *, name=None):
"""Add resource."""
return self.router.add_resource(path, name=name)
def get_info(self):
return {'path': self._path}
def url(self, name=None, **kwargs):
if name:
return self._path + self.router[name].url(**kwargs)
return self._path + '/'
示例3: __init__
def __init__(self, path, *, name=None):
super(ParentResource, self).__init__(name=name)
self._path = path.rstrip('/')
self.router = UrlDispatcher()
示例4: setUp
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.router = UrlDispatcher()
示例5: TestUrlDispatcher
class TestUrlDispatcher(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.router = UrlDispatcher()
def tearDown(self):
self.loop.close()
def make_request(self, method, path):
self.app = mock.Mock()
message = RawRequestMessage(method, path, HttpVersion(1, 1),
CIMultiDict(), [], False, False)
self.payload = mock.Mock()
self.transport = mock.Mock()
self.reader = mock.Mock()
self.writer = mock.Mock()
req = Request(self.app, message, self.payload,
self.transport, self.reader, self.writer)
return req
def make_handler(self):
@asyncio.coroutine
def handler(request):
return Response(request) # pragma: no cover
return handler
def test_system_route(self):
route = SystemRoute(HTTPCreated(reason='test'))
self.assertIsNone(route.match('any'))
with self.assertRaises(RuntimeError):
route.url()
self.assertEqual("<SystemRoute 201: test>", repr(route))
self.assertEqual(201, route.status)
self.assertEqual('test', route.reason)
def test_register_route(self):
handler = self.make_handler()
route = PlainRoute('GET', handler, 'test', '/handler/to/path')
self.router.register_route(route)
req = self.make_request('GET', '/handler/to/path')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(route, info.route)
self.assertIs(handler, info.handler)
self.assertEqual(info.route.name, 'test')
def test_register_route_checks(self):
self.assertRaises(
AssertionError, self.router.register_route, object())
handler = self.make_handler()
route = PlainRoute('GET', handler, 'test', '/handler/to/path')
self.router.register_route(route)
self.assertRaises(ValueError, self.router.register_route, route)
route = PlainRoute('GET', handler, '1bad name', '/handler/to/path')
self.assertRaises(ValueError, self.router.register_route, route)
route = PlainRoute('GET', handler, 'return', '/handler/to/path')
self.assertRaises(ValueError, self.router.register_route, route)
route = PlainRoute('GET', handler, 'test.test:test-test',
'/handler/to/path')
self.router.register_route(route)
def test_add_route_root(self):
handler = self.make_handler()
self.router.add_route('GET', '/', handler)
req = self.make_request('GET', '/')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_route_simple(self):
handler = self.make_handler()
self.router.add_route('GET', '/handler/to/path', handler)
req = self.make_request('GET', '/handler/to/path')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_with_matchdict(self):
handler = self.make_handler()
self.router.add_route('GET', '/handler/{to}', handler)
req = self.make_request('GET', '/handler/tail')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual({'to': 'tail'}, info)
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
#.........这里部分代码省略.........
示例6: TestUrlDispatcher
class TestUrlDispatcher(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.router = UrlDispatcher()
def tearDown(self):
self.loop.close()
def make_request(self, method, path):
self.app = mock.Mock()
message = RawRequestMessage(method, path, HttpVersion(1, 1),
CIMultiDict(), False, False)
self.payload = mock.Mock()
self.transport = mock.Mock()
self.reader = mock.Mock()
self.writer = mock.Mock()
req = Request(self.app, message, self.payload,
self.transport, self.reader, self.writer)
return req
def make_handler(self):
@asyncio.coroutine
def handler(request):
return Response(request) # pragma: no cover
return handler
def test_system_route(self):
route = SystemRoute(201, 'test')
self.assertIsNone(route.match('any'))
with self.assertRaises(RuntimeError):
route.url()
self.assertEqual("<SystemRoute 201: test>", repr(route))
self.assertEqual(201, route.status)
self.assertEqual('test', route.reason)
def test_register_route(self):
handler = self.make_handler()
route = PlainRoute('GET', handler, 'test', '/handler/to/path')
self.router.register_route(route)
req = self.make_request('GET', '/handler/to/path')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(route, info.route)
self.assertIs(handler, info.handler)
self.assertEqual(info.route.name, 'test')
def test_register_route_checks(self):
self.assertRaises(
AssertionError, self.router.register_route, object())
handler = self.make_handler()
route = PlainRoute('GET', handler, 'test', '/handler/to/path')
self.router.register_route(route)
self.assertRaises(ValueError, self.router.register_route, route)
def test_add_route_root(self):
handler = self.make_handler()
self.router.add_route('GET', '/', handler)
req = self.make_request('GET', '/')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_route_simple(self):
handler = self.make_handler()
self.router.add_route('GET', '/handler/to/path', handler)
req = self.make_request('GET', '/handler/to/path')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_with_matchdict(self):
handler = self.make_handler()
self.router.add_route('GET', '/handler/{to}', handler)
req = self.make_request('GET', '/handler/tail')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual({'to': 'tail'}, info)
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_with_name(self):
handler = self.make_handler()
self.router.add_route('GET', '/handler/to/path', handler,
name='name')
req = self.make_request('GET', '/handler/to/path')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual('name', info.route.name)
#.........这里部分代码省略.........
示例7: TestUrlDispatcher
class TestUrlDispatcher(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.router = UrlDispatcher()
def tearDown(self):
self.loop.close()
def make_request(self, method, path):
self.app = mock.Mock()
message = RawRequestMessage(method, path, HttpVersion(1, 1),
MultiDict(), False, False)
self.payload = mock.Mock()
self.transport = mock.Mock()
self.writer = mock.Mock()
req = Request(self.app, message, self.payload,
self.transport, self.writer, 15)
return req
def test_add_route_root(self):
handler = asyncio.coroutine(lambda req: Response(req))
self.router.add_route('GET', '/', handler)
req = self.make_request('GET', '/')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_route_simple(self):
handler = asyncio.coroutine(lambda req: Response(req))
self.router.add_route('GET', '/handler/to/path', handler)
req = self.make_request('GET', '/handler/to/path')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_with_matchdict(self):
handler = asyncio.coroutine(lambda req: Response(req))
self.router.add_route('GET', '/handler/{to}', handler)
req = self.make_request('GET', '/handler/tail')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual({'to': 'tail'}, info)
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_with_name(self):
handler = lambda req: Response(req)
self.router.add_route('GET', '/handler/to/path', handler,
name='name')
req = self.make_request('GET', '/handler/to/path')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual('name', info.route.name)
def test_add_with_tailing_slash(self):
handler = asyncio.coroutine(lambda req: Response(req))
self.router.add_route('GET', '/handler/to/path/', handler)
req = self.make_request('GET', '/handler/to/path/')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual({}, info)
self.assertIs(handler, info.handler)
def test_add_invalid_path(self):
with self.assertRaises(ValueError):
self.router.add_route('GET', '/{/', lambda req: None)
def test_add_url_invalid1(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post/{id', lambda: None)
def test_add_url_invalid2(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post/{id{}}', lambda: None)
def test_add_url_invalid3(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post/{id{}', lambda: None)
def test_add_url_invalid4(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post/{id"}', lambda: None)
def test_add_url_invalid5(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post"{id}', lambda: None)
def test_add_url_escaping(self):
handler = asyncio.coroutine(lambda req: Response(req))
self.router.add_route('GET', '/+$', handler)
req = self.make_request('GET', '/+$')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
#.........这里部分代码省略.........
示例8: TestUrlDispatcher
class TestUrlDispatcher(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.router = UrlDispatcher()
def tearDown(self):
self.loop.close()
def make_request(self, method, path):
self.app = mock.Mock()
message = RawRequestMessage(method, path, HttpVersion(1, 1), CIMultiDict(), False, False)
self.payload = mock.Mock()
self.transport = mock.Mock()
self.reader = mock.Mock()
self.writer = mock.Mock()
req = Request(self.app, message, self.payload, self.transport, self.reader, self.writer)
return req
def make_handler(self):
@asyncio.coroutine
def handler(request):
return Response(request) # pragma: no cover
return handler
def test_system_route(self):
route = SystemRoute(201, "test")
self.assertIsNone(route.match("any"))
with self.assertRaises(RuntimeError):
route.url()
self.assertEqual("<SystemRoute 201: test>", repr(route))
self.assertEqual(201, route.status)
self.assertEqual("test", route.reason)
def test_register_route(self):
handler = self.make_handler()
route = PlainRoute("GET", handler, "test", "/handler/to/path")
self.router.register_route(route)
req = self.make_request("GET", "/handler/to/path")
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(route, info.route)
self.assertIs(handler, info.handler)
self.assertEqual(info.route.name, "test")
def test_register_route_checks(self):
self.assertRaises(AssertionError, self.router.register_route, object())
handler = self.make_handler()
route = PlainRoute("GET", handler, "test", "/handler/to/path")
self.router.register_route(route)
self.assertRaises(ValueError, self.router.register_route, route)
route = PlainRoute("GET", handler, "1bad name", "/handler/to/path")
self.assertRaises(ValueError, self.router.register_route, route)
route = PlainRoute("GET", handler, "return", "/handler/to/path")
self.assertRaises(ValueError, self.router.register_route, route)
def test_add_route_root(self):
handler = self.make_handler()
self.router.add_route("GET", "/", handler)
req = self.make_request("GET", "/")
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_route_simple(self):
handler = self.make_handler()
self.router.add_route("GET", "/handler/to/path", handler)
req = self.make_request("GET", "/handler/to/path")
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_with_matchdict(self):
handler = self.make_handler()
self.router.add_route("GET", "/handler/{to}", handler)
req = self.make_request("GET", "/handler/tail")
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual({"to": "tail"}, info)
self.assertIs(handler, info.handler)
self.assertIsNone(info.route.name)
def test_add_with_name(self):
handler = self.make_handler()
self.router.add_route("GET", "/handler/to/path", handler, name="name")
req = self.make_request("GET", "/handler/to/path")
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual("name", info.route.name)
#.........这里部分代码省略.........
示例9: __init__
def __init__(self, application):
self._dispatcher = UrlDispatcher()
self._application = application
示例10: TestUrlDispatcher
class TestUrlDispatcher(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.router = UrlDispatcher()
def tearDown(self):
self.loop.close()
def make_request(self, method, path):
self.app = mock.Mock()
message = RawRequestMessage(method, path, HttpVersion(1, 1),
MultiDict(), False, False)
self.payload = mock.Mock()
self.transport = mock.Mock()
self.writer = mock.Mock()
req = Request(self.app, message, self.payload,
self.transport, self.writer, 15)
return req
def test_add_route_root(self):
handler = lambda req: Response(req)
self.router.add_route('GET', '/', handler)
req = self.make_request('GET', '/')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
def test_add_route_simple(self):
handler = lambda req: Response(req)
self.router.add_route('GET', '/handler/to/path', handler)
req = self.make_request('GET', '/handler/to/path')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual(0, len(info))
self.assertIs(handler, info.handler)
def test_add_with_matchdict(self):
handler = lambda req: Response(req)
self.router.add_route('GET', '/handler/{to}', handler)
req = self.make_request('GET', '/handler/tail')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual({'to': 'tail'}, info)
self.assertIs(handler, info.handler)
def test_add_with_tailing_slash(self):
handler = lambda req: Response(req)
self.router.add_route('GET', '/handler/to/path/', handler)
req = self.make_request('GET', '/handler/to/path/')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual({}, info)
self.assertIs(handler, info.handler)
def test_add_invalid_path(self):
with self.assertRaises(ValueError):
self.router.add_route('GET', '/{/', lambda req: None)
def test_add_url_invalid1(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post/{id', lambda: None)
def test_add_url_invalid2(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post/{id{}}', lambda: None)
def test_add_url_invalid3(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post/{id{}', lambda: None)
def test_add_url_invalid4(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post/{id"}', lambda: None)
def test_add_url_invalid5(self):
with self.assertRaises(ValueError):
self.router.add_route('post', '/post"{id}', lambda: None)
def test_add_url_escaping(self):
handler = lambda req: Response(req)
self.router.add_route('GET', '/+$', handler)
req = self.make_request('GET', '/+$')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertIs(handler, info.handler)
def test_match_second_result_in_table(self):
handler1 = lambda req: Response(req)
handler2 = lambda req: Response(req)
self.router.add_route('GET', '/h1', handler1)
self.router.add_route('POST', '/h2', handler2)
req = self.make_request('POST', '/h2')
info = self.loop.run_until_complete(self.router.resolve(req))
self.assertIsNotNone(info)
self.assertEqual({}, info)
self.assertIs(handler2, info.handler)
#.........这里部分代码省略.........
示例11: TestWebSendFile
class TestWebSendFile(unittest.TestCase):
def setUp(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(None)
self.router = UrlDispatcher()
def tearDown(self):
self.loop.close()
# def make_handler(self):
# @asyncio.coroutine
# def handler(request):
# return aiohttp.Response(request) # pragma: no cover
#
# return handler
def test_env_nosendfile(self):
directory = os.path.dirname(__file__)
with mock.patch.dict(os.environ, {'AIOHTTP_NOSENDFILE': '1'}):
route = web.StaticRoute(None, "/", directory)
file_sender = FileSender(resp_factory=route._response_factory,
chunk_size=route._chunk_size
)
self.assertEqual(file_sender._sendfile,
file_sender._sendfile_fallback)
def test_static_handle_eof(self):
loop = mock.Mock()
route = self.router.add_static('/st',
os.path.dirname(aiohttp.__file__))
with mock.patch('aiohttp.helpers.os') as m_os:
out_fd = 30
in_fd = 31
fut = helpers.create_future(self.loop)
m_os.sendfile.return_value = 0
file_sender = FileSender(resp_factory=route._response_factory,
chunk_size=route._chunk_size
)
file_sender._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False)
m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100)
self.assertTrue(fut.done())
self.assertIsNone(fut.result())
self.assertFalse(loop.add_writer.called)
self.assertFalse(loop.remove_writer.called)
def test_static_handle_again(self):
loop = mock.Mock()
route = self.router.add_static('/st',
os.path.dirname(aiohttp.__file__))
with mock.patch('aiohttp.helpers.os') as m_os:
out_fd = 30
in_fd = 31
fut = helpers.create_future(self.loop)
m_os.sendfile.side_effect = BlockingIOError()
file_sender = FileSender(resp_factory=route._response_factory,
chunk_size=route._chunk_size
)
file_sender._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False)
m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100)
self.assertFalse(fut.done())
loop.add_writer.assert_called_with(out_fd,
file_sender._sendfile_cb,
fut, out_fd, in_fd, 0, 100,
loop, True)
self.assertFalse(loop.remove_writer.called)
def test_static_handle_exception(self):
loop = mock.Mock()
route = self.router.add_static('/st',
os.path.dirname(aiohttp.__file__))
with mock.patch('aiohttp.helpers.os') as m_os:
out_fd = 30
in_fd = 31
fut = helpers.create_future(self.loop)
exc = OSError()
m_os.sendfile.side_effect = exc
file_sender = FileSender(resp_factory=route._response_factory,
chunk_size=route._chunk_size
)
file_sender._sendfile_cb(fut, out_fd, in_fd, 0, 100, loop, False)
m_os.sendfile.assert_called_with(out_fd, in_fd, 0, 100)
self.assertTrue(fut.done())
self.assertIs(exc, fut.exception())
self.assertFalse(loop.add_writer.called)
self.assertFalse(loop.remove_writer.called)