def test_basic_building(): """Basic URL building""" map = Map([ Rule('/', endpoint='index'), Rule('/foo', endpoint='foo'), Rule('/bar/<baz>', endpoint='bar'), Rule('/bar/<int:bazi>', endpoint='bari'), Rule('/bar/<float:bazf>', endpoint='barf'), Rule('/bar/<path:bazp>', endpoint='barp'), 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' assert_raises(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'
class Urls: def __init__(self, rules): self.map = Map(rules) self.urls = ContextVar("urls", default=self.map.bind('')) def iter_rules(self): return self.map.iter_rules() @contextmanager def _bind(self, urls): token = self.urls.set(urls) try: yield finally: self.urls.reset(token) def bind(self, *args, **kwargs): return self._bind(self.map.bind(*args, **kwargs)) def bind_to_environ(self, *args, **kwargs): return self._bind(self.map.bind_to_environ(*args, **kwargs)) def build(self, endpoint, values=None, method=None, force_external=False, append_unknown=True): urls = self.urls.get() path = urls.build(endpoint, values, method, force_external, append_unknown) if urls.url_scheme == 'file' and urls.server_name == '.': assert not force_external if path.endswith('/'): path = path + 'index.html' return os.path.relpath(path, os.path.dirname(urls.path_info)) return path def match(self, path=None, return_rule=False): urls = self.urls.get() if path is None: return urls.match(return_rule=return_rule) if urls.url_scheme == 'file' and urls.server_name == '.': path = os.path.normpath( os.path.join(os.path.dirname(urls.path_info), path)) if path.endswith("/index.html"): path = path[:-11] else: script_name = urls.script_name.rstrip("/") assert path.startswith(script_name) path = path[len(script_name):] return urls.match(path, return_rule=return_rule) def dispatch(self, *args, **kwargs): return self.urls.get().dispatch(*args, **kwargs) def current_url(self): return self.dispatch(lambda e, v: self.build(e, v))
def test_request_direct_charset_bug(): map = Map([Rule(u'/öäü/')]) adapter = map.bind('localhost', '/') try: adapter.match(u'/öäü') except RequestRedirect, e: assert e.new_url == 'http://localhost/%C3%B6%C3%A4%C3%BC/'
class JSONResolver(object): """Resolve JSON objects based on rules in URL map.""" def __init__(self, plugins=None, entry_point_group=None): """Initialize resolver with various plugins and entry point group.""" self.pm = pluggy.PluginManager('jsonresolver') self.pm.add_hookspecs(hookspec) for plugin in plugins or []: self.pm.register( importlib.import_module(plugin) ) if entry_point_group: self.pm.load_setuptools_entrypoints(entry_point_group) self.url_map = None def _build_url_map(self): """Build an URL map from registered plugins.""" self.url_map = Map() self.pm.hook.jsonresolver_loader(url_map=self.url_map) def resolve(self, url): """Resolve given URL and use regitered loader.""" if self.url_map is None: self._build_url_map() parts = urlsplit(url) loader, args = self.url_map.bind(parts.hostname).match(parts.path) return loader(**args)
def test_adapter_url_parameter_sorting(): """Optional adapter URL parameter sorting""" map = Map([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'
class Router: def __init__(self, services, server_name): self.services = services self.server_name = server_name url_map = [] for service in services: for handler in service.handlers: for route in handler.routes: url_map.append(Rule( route.path, methods=route.methods, endpoint=handler, )) self.url_map = Map(url_map) @functools.lru_cache(maxsize=1024) def lookup(self, path, method): url = self.url_map.bind(server_name=self.server_name) try: handler, arguments = url.match(path_info=path, method=method) except WZ_NotFound as ex: raise NotFound() from None except WZ_MethodNotAllowed as ex: raise MethodNotAllowed() from None except WZ_RequestRedirect as ex: raise HttpRedirect(ex.new_url, status=ex.code) return handler, arguments
def test_path(): """URL routing path converter behavior""" map = Map([ Rule('/', defaults={'name': 'FrontPage'}, endpoint='page'), Rule('/Special', endpoint='special'), Rule('/<int:year>', endpoint='year'), Rule('/<path:name>', endpoint='page'), Rule('/<path:name>/edit', endpoint='editpage'), Rule('/<path:name>/silly/<path:name2>', endpoint='sillypage'), Rule('/<path:name>/silly/<path:name2>/edit', endpoint='editsillypage'), Rule('/Talk:<path:name>', endpoint='talk'), Rule('/User:<username>', endpoint='user'), Rule('/User:<username>/<path:name>', endpoint='userpage'), Rule('/Files/<path:file>', endpoint='files'), ]) adapter = map.bind('example.org', '/') assert adapter.match('/') == ('page', {'name':'FrontPage'}) assert_raises(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':'******'}) assert adapter.match('/User:thomas/projects/werkzeug') == ('userpage', {'username':'******', 'name':'projects/werkzeug'}) assert adapter.match('/Files/downloads/werkzeug/0.2.zip') == ('files', {'file':'downloads/werkzeug/0.2.zip'})
def bind(self, server_name, script_name=None, subdomain=None, url_scheme='http', default_method='GET', path_info=None, query_args=None): org_adapter = _Map.bind(self, server_name, script_name, subdomain, subdomain, url_scheme, default_method, path_info, query_args) return self._convert_adapter(org_adapter)
def check_map(uri, url_root): """ return a tuple of the rule and kw. """ # TODO: Building the Map each time this is called seems like it could be more effiecent. result = [] try: result = db.execute( text(fetch_query_string( 'select_route_where_dynamic.sql'))).fetchall() except OperationalError as err: current_app.logger.error("OperationalError: %s", err) return (None, None) if result: #routes = result.as_dict() #(routes, col_names) = rowify(result, c.description) #current_app.logger.debug( [x['rule'] for x in routes] ) rules = map(lambda r: Rule(r['rule'], endpoint='dynamic'), result) d_map = Map(rules) map_adapter = d_map.bind(url_root) #current_app.logger.debug(uri) try: (rule, rule_kw) = map_adapter.match(path_info=uri, return_rule=True) #current_app.logger.debug(rule) return (str(rule), rule_kw) except HTTPException: pass return (None, {})
def __init__(self, worker, config, path): """ :param worker: The router worker controller within this Web service is started. :type worker: crossbar.worker.router.RouterController :param config: The Web service configuration item. :type config: dict """ resource.Resource.__init__(self) self._worker = worker self._config = config self._session_cache = {} self._realm_name = config.get('wamp', {}).get('realm', None) self._authrole = config.get('wamp', {}).get('authrole', 'anonymous') self._service_agent = worker.realm_by_name(self._realm_name).session # TODO: # We need to lookup the credentials for the current user based on the pre-established # HTTP session cookie, this will establish the 'authrole' the user is running as. # This 'authrole' can then be used to authorize the back-end topic call. # QUESTION: # Does the topic need the authid, if so, how do we pass it? # # This is our default (anonymous) session for unauthenticated users # router = worker._router_factory.get(self._realm_name) self._default_session = ApplicationSession(ComponentConfig(realm=self._realm_name, extra=None)) worker._router_session_factory.add(self._default_session, router, authrole=self._authrole) # Setup Jinja2 to point to our templates folder # templates_dir = os.path.abspath( os.path.join(self._worker.config.extra.cbdir, config.get("templates"))) env = Environment(loader=FileSystemLoader(templates_dir), autoescape=True) self.log.info( 'WapResource added on realm "{realm}" (authrole "{authrole}") using templates directory "{templates_dir}"', realm=hlid(self._realm_name), authrole=hlid(self._authrole), templates_dir=hlid(templates_dir)) # http://werkzeug.pocoo.org/docs/dev/routing/#werkzeug.routing.Map map = Map() # Add all our routes into 'map', note each route endpoint is a tuple of the # topic to call, and the template to use when rendering the results. for route in config.get('routes', {}): route_url = '/' + path + route.get('path') route_methods = [route.get('method')] route_endpoint = (route['call'], env.get_template(route['render'])) map.add(Rule(route_url, methods=route_methods, endpoint=route_endpoint)) self.log.info( 'WapResource route added (url={route_url}, methods={route_methods}, endpoint={route_endpoint})', route_url=route_url, route_methods=route_methods, route_endpoint=route_endpoint) # http://werkzeug.pocoo.org/docs/dev/routing/#werkzeug.routing.MapAdapter # http://werkzeug.pocoo.org/docs/dev/routing/#werkzeug.routing.MapAdapter.match self._map_adapter = map.bind('/')
def test_path(): """URL routing path converter behavior""" map = Map( [ Rule("/", defaults={"name": "FrontPage"}, endpoint="page"), Rule("/Special", endpoint="special"), Rule("/<int:year>", endpoint="year"), Rule("/<path:name>", endpoint="page"), Rule("/<path:name>/edit", endpoint="editpage"), Rule("/<path:name>/silly/<path:name2>", endpoint="sillypage"), Rule("/<path:name>/silly/<path:name2>/edit", endpoint="editsillypage"), Rule("/Talk:<path:name>", endpoint="talk"), Rule("/User:<username>", endpoint="user"), Rule("/User:<username>/<path:name>", endpoint="userpage"), Rule("/Files/<path:file>", endpoint="files"), ] ) adapter = map.bind("example.org", "/") assert adapter.match("/") == ("page", {"name": "FrontPage"}) assert_raises(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": "******"}) assert adapter.match("/User:thomas/projects/werkzeug") == ( "userpage", {"username": "******", "name": "projects/werkzeug"}, ) assert adapter.match("/Files/downloads/werkzeug/0.2.zip") == ("files", {"file": "downloads/werkzeug/0.2.zip"})
def test_adapter_url_parameter_sorting(): """Optional adapter URL parameter sorting""" map = Map([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" )
def check_map(uri, url_root): """ return a tuple of the rule and kw. """ # TODO: Building the Map each time this is called seems like it could be more effiecent. c = db.cursor() try: c.execute(fetch_query_string('select_route_where_dynamic.sql')) except sqlite3.OperationalError as err: current_app.logger.error("OperationalError: %s", err) return (None, None) result = c.fetchall() if result: (routes, col_names) = rowify(result, c.description) #current_app.logger.debug( [x['rule'] for x in routes] ) rules = map( lambda r: Rule(r['rule'], endpoint='dynamic'), routes ) d_map = Map( rules ) map_adapter = d_map.bind(url_root) #current_app.logger.debug(uri) try: (rule, rule_kw) = map_adapter.match(path_info=uri, return_rule=True) #current_app.logger.debug(rule) return (str(rule), rule_kw) except HTTPException: pass return (None, {})
def __init__(self, routes: List[Route]): mapping = Map([ Rule(route.path, endpoint=route.name, methods=route.methods) for route in routes ]) self.adapter = mapping.bind('') self.apps = {route.name: route.app for route in routes}
def test_external_building_with_port(): """Test external URL building with port number""" map = Map([ 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
def test_basic_route(self): rule = URITemplateRule(URITemplate('/browse/{id}'), endpoint='root') m = Map() m.add(rule) bm = m.bind('example.com') self.assertEqual('/browse/{id}', str(rule)) self.assertEqual(('', '/browse/321'), rule.build({'id': '321'})) self.assertEqual('/browse/321', bm.build('root', {'id': '321'}))
def test_request_redirect_default_subdomain(): map = Map([Rule(u'/foo', defaults={'bar': 42}, subdomain='test'), Rule(u'/foo/<int:bar>', subdomain='other')]) adapter = map.bind('localhost', '/', subdomain='other') try: adapter.match(u'/foo/42') except RequestRedirect, e: assert e.new_url == 'http://test.localhost/foo'
def test_request_redirect_default(): map = Map([Rule(u'/foo', defaults={'bar': 42}), Rule(u'/foo/<int:bar>')]) adapter = map.bind('localhost', '/') try: adapter.match(u'/foo/42') except RequestRedirect, e: assert e.new_url == 'http://localhost/foo'
def __init__(self, routes): self.routes = routes mapping = Map([ Rule(route.path, endpoint=route.name, methods=route.methods) for route in routes ]) self.adapter = mapping.bind('') self.routes = {route.name: route.consumer for route in routes}
def test_request_direct_charset_bug(): map = Map([Rule(u"/öäü/")]) adapter = map.bind("localhost", "/") try: adapter.match(u"/öäü") except RequestRedirect, e: print repr(e.new_url) assert e.new_url == "http://localhost/%C3%B6%C3%A4%C3%BC/"
class WebRouter(ServerHttpProtocol): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.api_root = '/' self.url_map = Map([ Rule('/', endpoint=api.ServerInfoEndpoint), Rule('/paged_query', endpoint=api.PagedQueryEndpoint), Rule('/metadata', endpoint=api.MetadataInfoEndpoint), Rule('/metadata/groups', endpoint=api.GroupCollectionEndpoint), Rule('/metadata/groups/<int:id>', endpoint=api.GroupEndpoint), Rule('/metadata/people', endpoint=api.PeopleCollectionEndpoint), Rule('/metadata/people/<int:id>', endpoint=api.PeopleEndpoint), Rule('/metadata/albums', endpoint=api.AlbumCollectionEndpoint), Rule('/metadata/albums/<int:id>', endpoint=api.AlbumEndpoint), Rule('/metadata/songs', endpoint=api.SongCollectionEndpoint), Rule('/metadata/songs/<int:id>', endpoint=api.SongEndpoint), Rule('/metadata/tracks', endpoint=api.TrackCollectionEndpoint), Rule('/metadata/tracks/<int:id>', endpoint=api.TrackEndpoint), Rule('/audio', endpoint=api.AudioCollectionEndpoint), Rule('/audio/<audio_name>.<format>', endpoint=api.AudioEndpoint), Rule('/users', endpoint=api.UserCollectionEndpoint), Rule('/users/<user_id>', endpoint=api.UserEndpoint), Rule('/users/<user_id>/playlists', endpoint=api.PlaylistCollectionEndpoint), Rule('/users/<user_id>/playlists/<pl_id>', endpoint=api.PlaylistEndpoint), Rule('/users/<user_id>/playlists/<pl_id>/<entry_id>', endpoint=api.PlaylistEntryEndpoint) ]) @asyncio.coroutine def handle_request(self, message, payload): now = time.time() urls = self.url_map.bind(message.headers['HOST'], self.api_root) try: endpoint_type, path_args = urls.match(message.path) except NotFound: endpoint_type, path_args = api.NotFoundEndpoint, {} endpoint = endpoint_type(self) response = yield from endpoint.handle(path_args, message, payload) self.log_access(message, None, response, time.time() - now)
class BrownAnt(object): """The app which could manage whole crawler system.""" def __init__(self): self.url_map = Map(strict_slashes=False, host_matching=True) def add_url_rule(self, host, rule_string, endpoint, **options): """Add a url rule to the app instance. The url rule is the same with Flask apps and other Werkzeug apps. :param host: the matched hostname. e.g. "www.python.org" :param rule_string: the matched path pattern. e.g. "/news/<int:id>" :param endpoint: the endpoint name as a dispatching key such as the qualified name of the object. """ rule = Rule(rule_string, host=host, endpoint=endpoint, **options) self.url_map.add(rule) def parse_url(self, url_string): """Parse the URL string with the url map of this app instance. :param url_string: the origin URL string. :returns: the tuple as `(url, url_adapter, query_args)`, the url is parsed by the standard library `urlparse`, the url_adapter is from the werkzeug bound URL map, the query_args is a multidict from the werkzeug. """ url = urlparse.urlparse(url_string) url_adapter = self.url_map.bind(server_name=url.hostname, url_scheme=url.scheme, path_info=url.path) query_args = url_decode(url.query) return url, url_adapter, query_args def dispatch_url(self, url_string): """Dispatch the URL string to the target endpoint function. :param url_string: the origin URL string. :returns: the return value of calling dispatched function. """ url, url_adapter, query_args = self.parse_url(url_string) try: endpoint, kwargs = url_adapter.match() except NotFound: raise NotSupported(url_string) handler = import_string(endpoint) request = Request(args=query_args) return handler(request, **kwargs) def mount_site(self, site): """Mount a supported site to this app instance. :param site: the site instance be mounted. """ site.play_actions(target=self)
def test_implicit_head(): """Test implicit HEAD in URL rules where GET is present""" url_map = Map([ Rule('/get', methods=['GET'], endpoint='a'), Rule('/post', methods=['POST'], endpoint='b') ]) adapter = url_map.bind('example.org') assert adapter.match('/get', method='HEAD') == ('a', {}) assert_raises(MethodNotAllowed, adapter.match, '/post', method='HEAD')
def test_basic_routing(): """Basic URL routing""" map = Map([Rule("/", endpoint="index"), Rule("/foo", endpoint="foo"), Rule("/bar/", endpoint="bar")]) adapter = map.bind("example.org", "/") assert adapter.match("/") == ("index", {}) assert adapter.match("/foo") == ("foo", {}) assert adapter.match("/bar/") == ("bar", {}) assert_raises(RequestRedirect, lambda: adapter.match("/bar")) assert_raises(NotFound, lambda: adapter.match("/blub"))
def test_basic_routing(): """Basic URL routing""" map = Map([ Rule('/', endpoint='index'), Rule('/foo', endpoint='foo'), Rule('/bar/', endpoint='bar') ]) adapter = map.bind('example.org', '/') assert adapter.match('/') == ('index', {}) assert adapter.match('/foo') == ('foo', {}) assert adapter.match('/bar/') == ('bar', {}) assert_raises(RequestRedirect, lambda: adapter.match('/bar')) assert_raises(NotFound, lambda: adapter.match('/blub')) adapter = map.bind('example.org', '/test') try: adapter.match('/bar') except RequestRedirect, e: assert e.new_url == 'http://example.org/test/bar/'
def test_build_append_unknown(): """Test the new append_unknown feature of URL building""" map = Map([ 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'
def test_basic_routing(): """Basic URL routing""" map = Map([ Rule('/', endpoint='index'), Rule('/foo', endpoint='foo'), Rule('/bar/', endpoint='bar') ]) adapter = map.bind('example.org', '/') assert adapter.match('/') == ('index', {}) assert adapter.match('/foo') == ('foo', {}) assert adapter.match('/bar/') == ('bar', {}) assert_raises(RequestRedirect, lambda: adapter.match('/bar')) assert_raises(NotFound, lambda: adapter.match('/blub')) adapter = map.bind('example.org', '/test') try: adapter.match('/bar') except RequestRedirect, e: print e.new_url assert e.new_url == 'http://example.org/test/bar/'
def test_defaults(): """URL routing defaults""" map = Map([Rule("/foo/", defaults={"page": 1}, endpoint="foo"), Rule("/foo/<int:page>", endpoint="foo")]) adapter = map.bind("example.org", "/") assert adapter.match("/foo/") == ("foo", {"page": 1}) assert_raises(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"
def test_build_only(self): rule = URITemplateRule('/browse/{id}', endpoint='root', build_only=True) m = Map() m.add(rule) bm = m.bind('example.com') self.assertIsNone(rule.match('/browse/123')) with self.assertRaises(NotFound): bm.match('/browse/123') self.assertEqual(('', '/browse/321'), rule.build({'id': '321'})) self.assertEqual('/browse/321', bm.build('root', {'id': '321'}))
class RouteHandler: def __init__(self): self._prefix = "" self._rules = Map() self._urls = self._rules.bind("/") def add(self, route): self._rules.add(Rule(route, endpoint=route)) def parse(self, route): res = self._urls.match(route) return res
def test_basic_routing(): map = Map([ Rule('/', endpoint='index'), Rule('/foo', endpoint='foo'), Rule('/bar/', endpoint='bar') ]) adapter = map.bind('example.org', '/') assert adapter.match('/') == ('index', {}) assert adapter.match('/foo') == ('foo', {}) assert adapter.match('/bar/') == ('bar', {}) raises(RequestRedirect, lambda: adapter.match('/bar')) raises(NotFound, lambda: adapter.match('/blub'))
def test_defaults(): map = Map([ Rule('/foo/', defaults={'page': 1}, endpoint='foo'), Rule('/foo/<int:page>', endpoint='foo') ]) adapter = map.bind('example.org', '/') assert adapter.match('/foo/') == ('foo', {'page': 1}) raises(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'
def decorator(cls): # parent is the parent class of the relation cls_name = cls.__name__.lower() handlers = getattr(self.__class__, "handlers", None) if _rule_re.match(route): ######################################## # new style Werkzeug route ######################################## r = Rule(route, endpoint=cls_name) m = Map() m.add(r) c = m.bind( cfg.server_settings["host"] + ":" + cfg.server_settings["host"], "/") r.compile() #print("r1: " + str(r._regex.pattern)) pattern = r._regex.pattern.replace('^\|', "") #print("r1: " + str(pattern)) fin_route = pattern # convert the HTTP Methods in dispatch to lowercase dispatch_lower = dict( (k.lower(), v) for k, v in dispatch.items()) route_tuple = (fin_route, cls, dispatch_lower) handlers.append((route_tuple, pos)) else: ################################### # old style regex route ################################### # BETA: this regex is added to every route to make # 1.the slash at the end optional # 2.it possible to add a .format paramter. # Example: route = /test -> also test.json will work # Example: route = /test/([0-9]+) -> also /test/12.xml will work if cfg.beta_settings["dot_format"]: fin_route = route + r"(?:/?\.\w+)?/?" else: fin_route = route # convert the HTTP Methods in dispatch to lowercase dispatch_lower = dict( (k.lower(), v) for k, v in dispatch.items()) route_tuple = (fin_route, cls, dispatch_lower) #route_tuple = (fin_route,cls, dispatch) handlers.append((route_tuple, pos)) #print("handlers: " + str(self.handlers)) #print("ROUTING: added route for: " + cls.__name__ + ": " + route + " -> " + fin_route + " dispatch") print( "STD ROUTE (+) : handler: {}, route: {}, fin_route: {}, dispatch(lower): {} " .format(str(cls.__name__), route, fin_route, str(dispatch_lower))) return cls
def test_defaults(): """URL routing defaults""" map = Map([ Rule('/foo/', defaults={'page': 1}, endpoint='foo'), Rule('/foo/<int:page>', endpoint='foo') ]) adapter = map.bind('example.org', '/') assert adapter.match('/foo/') == ('foo', {'page': 1}) assert_raises(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'
def scanRoutes(megamodules=None): # produce only the megamodule rules for the router mapperRules = [] for cls in getByClass(BasePage, megamodules): for route in cls.routes: mapperRules.append(route.getRule(cls)) GLOBAL['routemap'] = Map(mapperRules) # produce all rules for the adapter adapterRules = [] for cls in getByClass(BasePage): for route in cls.routes: adapterRules.append(route.getRule(cls)) adapterMap = Map(adapterRules) GLOBAL['urls'] = adapterMap.bind(CONFIG['BASE_URL'], '/')
def test_greedy(): map = Map([ Rule('/foo', endpoint='foo'), Rule('/<path:bar>', endpoint='bar'), Rule('/<path:bar>/<path:blub>', endpoint='bar') ]) adapter = map.bind('example.org', '/') assert adapter.match('/foo') == ('foo', {}) assert adapter.match('/blub') == ('bar', {'bar': 'blub'}) assert adapter.match('/he/he') == ('bar', {'bar': 'he', 'blub': 'he'}) assert adapter.build('foo', {}) == '/foo' assert adapter.build('bar', {'bar': 'blub'}) == '/blub' assert adapter.build('bar', {'bar': 'blub', 'blub': 'bar'}) == '/blub/bar'
def test_host_matching(): m = Map([ Rule('/', endpoint='index', host='www.<domain>'), Rule('/', endpoint='files', host='files.<domain>'), Rule('/foo/', defaults={'page': 1}, host='www.<domain>', endpoint='x'), 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 RequestRedirect, e: assert e.new_url == 'http://www.example.com/foo/'
def test_werkzeug_converter(): from werkzeug.routing import Map, Rule from werkzeug.exceptions import NotFound m = Map([ Rule('/debtors/<i64:debtorId>', endpoint='debtors'), ], converters={'i64': c.Int64Converter}) urls = m.bind('example.com', '/') # Test URL match: assert urls.match('/debtors/0') == ('debtors', {'debtorId': 0}) assert urls.match('/debtors/1') == ('debtors', {'debtorId': 1}) assert urls.match('/debtors/9223372036854775807') == ('debtors', { 'debtorId': 9223372036854775807 }) assert urls.match('/debtors/9223372036854775808') == ('debtors', { 'debtorId': -9223372036854775808 }) assert urls.match('/debtors/18446744073709551615') == ('debtors', { 'debtorId': -1 }) with pytest.raises(NotFound): assert urls.match('/debtors/01') with pytest.raises(NotFound): assert urls.match('/debtors/1x') with pytest.raises(NotFound): assert urls.match('/debtors/18446744073709551616') with pytest.raises(NotFound): assert urls.match('/debtors/-1') # Test URL build: assert urls.build('debtors', {'debtorId': 0}) == '/debtors/0' assert urls.build('debtors', {'debtorId': 1}) == '/debtors/1' assert urls.build( 'debtors', {'debtorId': 9223372036854775807}) == '/debtors/9223372036854775807' assert urls.build( 'debtors', {'debtorId': -9223372036854775808}) == '/debtors/9223372036854775808' with pytest.raises(ValueError): assert urls.build('debtors', {'debtorId': 9223372036854775808}) with pytest.raises(ValueError): assert urls.build('debtors', {'debtorId': -9223372036854775809}) with pytest.raises(ValueError): assert urls.build('debtors', {'debtorId': '1x'})
def test_greedy(): """URL routing greedy settings""" map = Map([ Rule('/foo', endpoint='foo'), Rule('/<path:bar>', endpoint='bar'), Rule('/<path:bar>/<path:blub>', endpoint='bar') ]) adapter = map.bind('example.org', '/') assert adapter.match('/foo') == ('foo', {}) assert adapter.match('/blub') == ('bar', {'bar': 'blub'}) assert adapter.match('/he/he') == ('bar', {'bar': 'he', 'blub': 'he'}) assert adapter.build('foo', {}) == '/foo' assert adapter.build('bar', {'bar': 'blub'}) == '/blub' assert adapter.build('bar', {'bar': 'blub', 'blub': 'bar'}) == '/blub/bar'
def test_method_fallback(): """Test that building falls back to different rules""" map = Map([ Rule('/', endpoint='index', methods=['GET']), Rule('/<name>', endpoint='hello_name', methods=['GET']), Rule('/select', endpoint='hello_select', methods=['POST']), Rule('/search_get', endpoint='search', methods=['GET']), 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'
def test_greedy(): """URL routing greedy settings""" map = Map( [ Rule("/foo", endpoint="foo"), Rule("/<path:bar>", endpoint="bar"), Rule("/<path:bar>/<path:blub>", endpoint="bar"), ] ) adapter = map.bind("example.org", "/") assert adapter.match("/foo") == ("foo", {}) assert adapter.match("/blub") == ("bar", {"bar": "blub"}) assert adapter.match("/he/he") == ("bar", {"bar": "he", "blub": "he"}) assert adapter.build("foo", {}) == "/foo" assert adapter.build("bar", {"bar": "blub"}) == "/blub" assert adapter.build("bar", {"bar": "blub", "blub": "bar"}) == "/blub/bar"
def test_alias_redirects(): m = Map([ Rule('/', endpoint='index'), Rule('/index.html', endpoint='index', alias=True), Rule('/users/', defaults={'page': 1}, endpoint='users'), Rule('/users/index.html', defaults={'page': 1}, alias=True, endpoint='users'), Rule('/users/page/<int:page>', endpoint='users'), 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 RequestRedirect, e: assert e.new_url == 'http://example.com' + new_url else:
def build_adapter(app: Flask) -> MapAdapter: """Build a :class:`.MapAdapter` from configured URLs.""" # Get the base URLs (configured in this package). configured_urls = {url[0]: url for url in base_config.URLS} # Privilege ARXIV_URLs set on the application config. current_urls = app.config.get('URLS', []) if current_urls: configured_urls.update({url[0]: url for url in current_urls}) url_map = Map([ Rule(pattern, endpoint=name, host=host, build_only=True) for name, pattern, host in configured_urls.values() ], converters={'arxiv': ArXivConverter}, host_matching=True) scheme = app.config.get('EXTERNAL_URL_SCHEME', 'https') base_host = app.config.get('BASE_SERVER', 'arxiv.org') adapter: MapAdapter = url_map.bind(base_host, url_scheme=scheme) return adapter
def test_greedy_path_converter(): # this test is mostly to document behavior router = Map(converters={"path": GreedyPathConverter}, merge_slashes=False) router.add(Rule("/test-bucket/<path:p>")) router.add(Rule("/some-route/<path:p>/bar")) matcher = router.bind("") # open-ended case assert matcher.match("/test-bucket//foo/bar") == (None, {"p": "/foo/bar"}) assert matcher.match("/test-bucket//foo//bar") == (None, {"p": "/foo//bar"}) assert matcher.match("/test-bucket//foo/bar/") == (None, {"p": "/foo/bar/"}) # with a matching suffix assert matcher.match("/some-route//foo/bar") == (None, {"p": "/foo"}) assert matcher.match("/some-route//foo//bar") == (None, {"p": "/foo/"}) assert matcher.match("/some-route//foo/bar/bar") == (None, {"p": "/foo/bar"}) with pytest.raises(NotFound): matcher.match("/some-route//foo/baz")
def test_complex_routing_rules(): from werkzeug.routing import Rule, Map m = Map([ Rule('/', endpoint='index'), Rule('/<int:blub>', endpoint='an_int'), Rule('/<blub>', endpoint='a_string'), Rule('/foo/', endpoint='nested'), Rule('/foobar/', endpoint='nestedbar'), Rule('/foo/<path:testing>/', endpoint='nested_show'), Rule('/foo/<path:testing>/edit', endpoint='nested_edit'), Rule('/users/', endpoint='users', defaults={'page': 1}), Rule('/users/page/<int:page>', endpoint='users'), Rule('/foox', endpoint='foox'), Rule('/<path:bar>/<path:blub>', endpoint='barx_path_path') ]) a = m.bind('example.com') assert a.match('/') == ('index', {}) assert a.match('/42') == ('an_int', {'blub': 42}) assert a.match('/blub') == ('a_string', {'blub': 'blub'}) assert a.match('/foo/') == ('nested', {}) assert a.match('/foobar/') == ('nestedbar', {}) assert a.match('/foo/1/2/3/') == ('nested_show', {'testing': '1/2/3'}) assert a.match('/foo/1/2/3/edit') == ('nested_edit', {'testing': '1/2/3'}) assert a.match('/users/') == ('users', {'page': 1}) assert a.match('/users/page/2') == ('users', {'page': 2}) assert a.match('/foox') == ('foox', {}) assert a.match('/1/2/3') == ('barx_path_path', {'bar': '1', 'blub': '2/3'}) assert a.build('index') == '/' assert a.build('an_int', {'blub': 42}) == '/42' assert a.build('a_string', {'blub': 'test'}) == '/test' assert a.build('nested') == '/foo/' assert a.build('nestedbar') == '/foobar/' assert a.build('nested_show', {'testing': '1/2/3'}) == '/foo/1/2/3/' assert a.build('nested_edit', {'testing': '1/2/3'}) == '/foo/1/2/3/edit' assert a.build('users', {'page': 1}) == '/users/' assert a.build('users', {'page': 2}) == '/users/page/2' assert a.build('foox') == '/foox' assert a.build('barx_path_path', {'bar': '1', 'blub': '2/3'}) == '/1/2/3'
def test_double_defaults(): for prefix in '', '/aaa': m = Map([ Rule(prefix + '/', defaults={'foo': 1, 'bar': False}, endpoint='x'), Rule(prefix + '/<int:foo>', defaults={'bar': False}, endpoint='x'), Rule(prefix + '/bar/', defaults={'foo': 1, 'bar': True}, endpoint='x'), 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/'
def do_GET(self): from werkzeug.routing import Map, Rule from werkzeug.exceptions import NotFound, MethodNotAllowed from oorq.oorq import setup_redis_connection from jinja2 import Template from rq import cancel_job from rq.job import Job from rq.exceptions import NoSuchJobError import times setup_redis_connection() m = Map([Rule('/job/<string:job>', endpoint='job'), Rule('/job/<string:job>/download', endpoint='download'), Rule('/job/<string:job>/cancel', endpoint='cancel')]) urls = m.bind('') try: endpoint, params = urls.match(self.path) job = Job.fetch(params['job']) self.send_response(200) if endpoint in ('job', 'cancel'): running_time = times.now() - job.enqueued_at if endpoint == 'cancel': cancel_job(job.id) self.send_header('Content-Type', 'text/html') self.end_headers() content = Template(get_template('jobs.html')) self.wfile.write(content.render(job=job, rt=running_time)) elif endpoint == 'download' and job.status == 'finished': self.send_header('Content-Type', 'application/%s' % job.meta['format']) self.send_header('Content-Length', len(job.result[0])) self.send_header('Content-Disposition', 'attachment;' 'filename=report.%s' % job.meta['format']) self.end_headers() self.wfile.write(job.result[0]) except (NotFound, NoSuchJobError): self.send_response(404) self.end_headers() except MethodNotAllowed: self.send_response(405) self.end_headers()
class Parser(object): def __init__(self): self.url_map = Map(strict_slashes=False, host_matching=True, redirect_defaults=False) def add_url_rule(self, host, rule_string, endpoint, **options): rule = Rule(rule_string, host=host, endpoint=endpoint, **options) self.url_map.add(rule) def parse_url(self, url_string): url = urllib.parse.urlparse(url_string) url_adapter = self.url_map.bind(server_name=url.hostname, url_scheme=url.scheme, path_info=url.path) query_args = url_decode(url.query) return url, url_adapter, query_args def dispatch_url(self, url_string, page_raw, **_kwargs): url, url_adapter, query_args = self.parse_url(url_string) try: endpoint, kwargs = url_adapter.match() kwargs.update(query_args) except NotFound: raise NotSupported(url_string) for k, v in kwargs.items(): if isinstance(v, (tuple, list)) and len(v) == 1: kwargs[k] == v[0] kwargs.update(_kwargs) handler = import_string(endpoint) return handler(url_string, page_raw, kwargs) def mount_site(self, site_string): site = import_string(site_string) site.play_actions(target=self)
def get_event_json(event_slug): """ Fetch the event json from the configured event source (EVENTICS_CONFIG['EVENT_SOURCE']). Returns the JSON and a status code """ # First, construct the url from EVENT_SOURCE, which uses Werkzeug URL # placeholders the same as our Flask url. This means constructing a simple # URL mapping. source_url_parts = urlparse(EVENTICS_CONFIG['EVENT_SOURCE']) source_map = Map([ Rule(source_url_parts.path, endpoint="event_source") ]) source_adapter = source_map.bind('') source_url_path = source_adapter.build('event_source', {'event_slug': event_slug}) source_url = urlunparse(source_url_parts._replace(path=source_url_path)) source_response = requests.get(source_url) try: return source_response.json(), source_response.status_code except ValueError: return {}, source_response.status_code
def test_basic_building(): """Basic URL building""" map = Map( [ Rule("/", endpoint="index"), Rule("/foo", endpoint="foo"), Rule("/bar/<baz>", endpoint="bar"), Rule("/bar/<int:bazi>", endpoint="bari"), Rule("/bar/<float:bazf>", endpoint="barf"), Rule("/bar/<path:bazp>", endpoint="barp"), 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" assert_raises(BuildError, lambda: adapter.build("urks"))