class RouterApp: """ Route request to the matching wsgiapp. """ def __init__(self,mode): self.map = Mapper() self.__routing_table = {}; # Maps path to app. self.mode = mode # HTTP POST json # -> webob (maybe no need?) def __call__(self, environ, start_response): req = Request(environ); # print 'env:\n', environ # print 'route:\n', req.path_qs # print 'match:\n', self.map.match(req.path_qs) match = self.map.match(req.path_qs) if match: m = match['middleware'] h = match['handler'] o = self.__routing_table[m] if o is not None: environ['_HANDLER'] = h return o(environ, start_response) err = exc.HTTPNotFound('NO SERVICE FOUND') return err(environ, start_response) def add_route(self, pat, mid, han): if mid not in self.__routing_table: # middleware being SINGELTON self.__routing_table[mid] = \ middleware_factory(mid,self.mode); self.map.connect(pat,middleware=mid,handler=han)
def make_map(config): """Create, configure and return the routes Mapper""" mapper = Mapper() connect = mapper.connect # For backwards compatibility with 0.9.7. mapper.explicit = False # Note that all of this are relative to the base path, /api. if 'pycloud.api.encrypted' in config and config['pycloud.api.encrypted'] == 'true': connect('command', '/command', controller='encrypted', action='command') else: # Service commands. connect('list', '/services', controller='services', action='list') connect('find', '/services/get', controller='services', action='find') # SVM commands. connect('startvm', '/servicevm/start', controller='servicevm', action='start') connect('stopvm', '/servicevm/stop', controller='servicevm', action='stop') # Appcommands. connect('getAppList', '/apps', controller='apppush', action='getList') connect('getApp', '/apps/get', controller='apppush', action='getApp') # Metadata commands. connect('metadata', '/system', controller='cloudlet', action='metadata') return mapper
class App(object): def __init__(self): print "step in App.__init__()..." self.myjob = MyJob() self.m = Mapper() self.m.connect('/myjob/{action}/{id}', controller=MyJob) self.router = middleware.RoutesMiddleware(self.dispatch, self.m) @wsgify def dispatch(self, req): print "step in App.dispatch()..." match = req.environ['wsgiorg.routing_args'][1] #print "wsgiorg.routing_args|match: %s\r\n%s\r\n" % (match,req.environ['wsgiorg.routing_args']) if not match: return 'error url: %s\r\n' % req.environ['PATH_INFO'] action = match['action'] if hasattr(self.myjob, action): func = getattr(self.myjob, action) ret = func() return ret else: return "has no action:%s in %s \r\n" % (action, controller) @wsgify def __call__(self, req): print "step in __call__()" return self.router
def get_map(): " This function returns mapper object for dispatcher " map = Mapper() # Add routes here urlmap(map, [ ('/', 'controllers#index'), ('/write', 'controllers#write'), ('/read', 'controllers#read'), ('/clean', 'controllers#clean'), ('/reset', 'controllers#reset') ]) # Old style map connecting #map.connect('Route_name', '/route/url', controller='controllerName', #action='actionName') if DEBUG: r = [Route(None, '/{path_info:.*}', controller='noodles.utils.static', action='index', path=os.path.join(os.getcwd(), 'static'), auth=True)] map.extend(r, '/static') return map
def make_app(self, req): map = Mapper() map.connect("index", "/", method="index") results = map.routematch(environ=req.environ) if results: match, route = results req.urlvars = ((), match) kwargs = match.copy() method = kwargs.pop("method") return getattr(self, method)(req, **kwargs) else: public_path = os.path.join(os.path.dirname(__file__), "public") if not os.path.exists(public_path): return exc.HTTPNotFound() path = req.path if path.startswith("/"): path = path[1:] public_file_path = os.path.join(public_path, path) if os.path.exists(public_file_path): if path.endswith(".css"): req.response.content_type = "text/css" elif path.endswith(".js"): req.response.content_type = "text/javascript" return open(public_file_path, "r").read().strip() else: return exc.HTTPNotFound()
def testManyPages(): """ Test: Tries to fit 100 items on 15-item pages """ from routes import Mapper items = range(100) # Create routes mapper so that webhelper can create URLs # using routes.url_for() map = Mapper() map.connect(':controller') page = Page(items, current_page=0, items_per_page=15) assert page.current_page==1 assert page.first_item==0 assert page.last_item==14 assert page.first_page==1 assert page.last_page==7 assert page.items_per_page==15 assert page.item_count==100 assert page.page_count==7 # Test deprecated navigator() assert page.navigator()=='[<strong>1</strong>] <a href="/content?page_nr=2">2</a> <a href="/content?page_nr=3">3</a> .. <a href="/content?page_nr=7">7</a>' assert page.pager()=='<span class="pager_curpage">1</span> <a href="/content?page_nr=2" class="pager_link">2</a> <a href="/content?page_nr=3" class="pager_link">3</a> <span class="pager_dotdot">..</span> <a href="/content?page_nr=7" class="pager_link">7</a>' assert page.pager(separator='_')=='<span class="pager_curpage">1</span>_<a href="/content?page_nr=2" class="pager_link">2</a>_<a href="/content?page_nr=3" class="pager_link">3</a>_<span class="pager_dotdot">..</span>_<a href="/content?page_nr=7" class="pager_link">7</a>' assert page.pager(link_var='xy')=='<span class="pager_curpage">1</span> <a href="/content?xy=2" class="pager_link">2</a> <a href="/content?xy=3" class="pager_link">3</a> <span class="pager_dotdot">..</span> <a href="/content?xy=7" class="pager_link">7</a>' assert page.pager(link_attr={'style':'s1'},curpage_attr={'style':'s2'},dotdot_attr={'style':'s3'})=='<span style="s2">1</span> <a href="/content?page_nr=2" style="s1">2</a> <a href="/content?page_nr=3" style="s1">3</a> <span style="s3">..</span> <a href="/content?page_nr=7" style="s1">7</a>'
def getMapper(self): if not self.__mapper__: mapper = Mapper() for name, route, controller, action in self.getUrls(): mapper.connect(name, route, controller=controller, action=action) self.__mapper__ = mapper return self.__mapper__
class Route(object): def __init__(self): self.map = Mapper() self.map.resource("server", "servers", controller="services", collection={'detail': 'GET'}, member={'action': 'POST'})
class API(object): """Our REST API WSGI application.""" def __init__(self, log): self.log = log self.mapper = Mapper() self.controllers = {} self.mapper.collection("routes", "route", path_prefix="/route", controller="route", collection_actions=['index', 'create'], member_actions=['show', 'delete'], member_prefix="/{route}", formatted=False) def add(self, name, controller): self.controllers[name] = controller def create_app(self): return RoutesMiddleware( self, self.mapper, use_method_override=False, singleton=False) @wsgify def __call__(self, request): # handle incoming call. depends on the routes middleware. url, match = request.environ['wsgiorg.routing_args'] if match is None or 'controller' not in match: raise HTTPNotFound() resource = self.controllers[match.pop('controller')] action = match.pop('action') return getattr(resource, action)(request, url, **match)
def __init__(self): a = Controller() _map = Mapper() """路由匹配条件1""" # map.connect('/images',controller=a, # action='search', # conditions={'method':['GET']}) """路由匹配条件2""" # map.connect('name',"/{action}/{pid}",controller=a) """路由匹配条件3""" # map.resource("message","messages",controller=a,collection={'search':'GET'}) """路由匹配条件4""" # map.resource('message', 'messages',controller=a, # collection={'list_many':'GET','create_many':'POST'}, # member={'update_many':'POST','delete_many':'POST'}) """路由匹配条件5""" _map.resource('message', 'messages', controller=a, path_prefix='/{projectid}', collection={'list_many': 'GET', 'create_many': 'POST'}, member={'update_many': 'POST', 'delete_many': 'POST'}) # _map.resource('type', 'types', controller=other_controller, # parent_resource=dict(member_name='message', # collection_name='messages'), # path_prefix='{projectid}/%s/:%s_id' % ('nex', 'nexs')) self.route = middleware.RoutesMiddleware(self._dispatch, _map)
class BaseApplication(object): special_vars = ['controller','action'] def __init__(self, conf): self.mapper = Mapper() self.mapper.connect('/test',controller = TestController, conditions = dict(method=['PUT'])) self.mapper.connect('/test',controller = TestController, conditions = dict(method=['GET'])) def __call__(self, env, start_response): req = Request(env) return self.handle_request(req)(env, start_response) def handle_request(self, req): print 'into mapping' results = self.mapper.routematch(environ=req.environ) print 'results --- after mapping' print '---- show result -----' print results match, route = results controller = match['controller'](self) try: handler = getattr(controller, req.method) except AttributeError: return HTTPMethodNotAllowed(request = req) #getattr(handler, 'publicly_accessible') kwargs = match.copy() for attr in self.special_vars: if attr in kwargs: del kwargs[attr] #return handler(req, **kwargs) return handler(req, **kwargs)
def __init__(self, *args, **kw): super(RoutedController, self).__init__(*args, **kw) routes = [] for name in dir(self): value = getattr(self.__class__, name, None) if value is None: continue deco = None if inspect.ismethod(value): # pragma: no cover # PY2 deco = Decoration.get_decoration(value.__func__) elif inspect.isfunction(value): # pragma: no cover # PY3 deco = Decoration.get_decoration(value) if deco is None: continue if hasattr(deco, '_tgext_routes'): routes.extend(deco._tgext_routes) if routes: instance_mapper = Mapper() if self.mapper is not None: instance_mapper.extend(self.mapper.matchlist) instance_mapper.extend(routes) self.mapper = instance_mapper
def test_redirect_middleware(): map = Mapper(explicit=False) map.minimization = True map.connect('myapp/*path_info', controller='myapp') map.redirect("faq/{section}", "/static/faq/{section}.html") map.redirect("home/index", "/", _redirect_code='301 Moved Permanently') map.create_regs(['content', 'myapp']) app = TestApp(RoutesMiddleware(simple_app, map)) res = app.get('/') assert 'matchdict items are []' in res res = app.get('/faq/home') eq_('302 Found', res.status) eq_(res.headers['Location'], '/static/faq/home.html') res = app.get('/myapp/some/other/url') print res assert b"matchdict items are [('action', " + repr(u'index').encode() + \ b"), ('controller', " + repr(u'myapp').encode() + \ b"), ('path_info', 'some/other/url')]" in res assert "'SCRIPT_NAME': '/myapp'" in res assert "'PATH_INFO': '/some/other/url'" in res res = app.get('/home/index') assert '301 Moved Permanently' in res.status eq_(res.headers['Location'], '/')
def setup_routes(self): map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) # Setup a default route for the root of object dispatch map.connect('*url', controller=self.root_controller, action='routes_placeholder') config['routes.map'] = map
class Application(object): def __init__(self): self.map = Mapper() self.map.connect('app1', '/app1url', app=app1) self.map.connect('app2', '/app2url', app=app2) def __call__(self, environ, start_response): match = self.map.routematch(environ=environ) if not match: return self.error404(environ, start_response) return match[0]['app'](environ, start_response) def error404(self, environ, start_response): html = b"""\ <html> <head> <title>404 - Not Found</title> </head> <body> <h1>404 - Not Found</h1> </body> </html> """ headers = [ ('Content-Type', 'text/html'), ('Content-Length', str(len(html))) ] start_response('404 Not Found', headers) return [html]
def __new__(cls, name, bases, dct): result = type.__new__(cls, name, bases, dct) if type(bases[0]) == type: return result if not hasattr(result, 'mapping'): raise TypeError('Route application without mapping.') from routes import Mapper mapper = Mapper() controllers = {} controller_map = {} for m in result.mapping: name = m[0].split('/', 1)[0] internal = str(id(m[1])) controllers[internal] = m[1] controller_map[m[1]] = internal kwargs = {} if len(m) >= 3 and not m[2] is None: kwargs['requirements'] = m[2] if len(m) == 4: kwargs.update(m[3]) mapper.connect(name, m[0], controller=internal, **kwargs) mapper.create_regs(controllers.keys()) result._routes_mapper = mapper result._routes_controllers = controllers result._controller_map = controller_map return result
class URLMapper(): """ Unlike the normal routes.Mapper, URLMapper works on urls with scheme, etc... Except, right now it doesn't really; eventually, make this match stuff """ def __init__(self): self.mapper = Mapper() self._add_routes() def _add_routes(self): """ override this in the subclass to add routes at create-time """ pass def make_path_with_query(self, parsed): if parsed.query: return parsed.path + '/' + parsed.query return parsed.path def match(self, uri): parsed = urlsplit(uri, 'http') path = self.make_path_with_query(parsed) if not path: return None return self.mapper.match(path) def connect(self, *args, **kwargs): #domain = kwargs.get('domain', '_default') return self.mapper.connect(*args, **kwargs)
class SensorHandler(tornado.web.RequestHandler): """Uses an aysnchronous call to an RPC server to calculate fib(x). As with examples of asynchronous HTTP calls, this request will not finish until the remote response is received.""" def initialize(self,database): self.mapper=Mapper() self.mapper.connect(None,"/{action}/{exchange}/{queue}") self.mapper.connect(None,"/{action}/{exchange}/") ## need to know something about the exchanges and queues in the ## broker #self.cl = Client('localhost:55672', 'guest', 'guest') def post(self, number=''): global cl request = self.request self.data = request.body result = self.mapper.match(request.uri) self.queue ='' try: self.queue = result['queue'] except: pass; self.pika_client = self.application.settings.get('pika_client') self.mq_ch = self.pika_client.channel self.corr_id = str(uuid.uuid4()) self.exchange= result['exchange'] try: pub=self.mq_ch.basic_publish(exchange=self.exchange, routing_key=self.queue,body=self.data) response={"Response":"Message sent"} self.write(json.dumps(response)) except: response={"Reponse":"Error publishing msg to exchange"} self.write(json.dumps(response))
def make_app(self, req): map = Mapper() map.connect('index', '/', method='index') results = map.routematch(environ=req.environ) if results: match, route = results req.urlvars = ((), match) kwargs = match.copy() method = kwargs.pop('method') return getattr(self, method)(req, **kwargs) else: public_path = os.path.join(os.path.dirname(__file__), 'public') if not os.path.exists(public_path): return exc.HTTPNotFound() path = req.path if path.startswith('/'): path = path[1:] public_file_path = os.path.join(public_path, path) if os.path.exists(public_file_path): if path.endswith('.css'): req.response.content_type = 'text/css' elif path.endswith('.js'): req.response.content_type = 'text/javascript' return open(public_file_path, 'r').read().strip() else: return exc.HTTPNotFound()
def __init__(self): print '__init__' self.controller = Test() mapper = Mapper() mapper.connect('blog', '/blog/{action}/{id}', controller=Test,conditions={'method': ['GET']}) mapper.redirect('/', '/blog/index/1') self.router = middleware.RoutesMiddleware(self.dispatch, mapper)
class MyResourceRouter(object): def __init__(self): route_name = 'resource' route_path = 'resor' my_application = Application(TestAction()) self.mapper = Mapper() self.mapper.resource(route_name, route_path, controller=my_application) self.mapper.connect('resconnct', '/getkey', controller=my_application, action='getkey', conditions={'method':['GET']}) self._router = routes.middleware.RoutesMiddleware(self._dispatch, self.mapper) @webob.dec.wsgify(RequestClass=webob.Request) def __call__(self, req): print 'MyRouter is invoked' return self._router @staticmethod @webob.dec.wsgify(RequestClass=webob.Request) def _dispatch(req): print 'RoutesMiddleware is invoked, calling the dispatch back' match_dict = req.environ['wsgiorg.routing_args'][1] if not match_dict: return webob.exc.HTTPNotFound() app = match_dict['controller'] return app
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = False mc = map.connect # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved mc('/error/{action}', controller='error') mc('/error/{action}/{id}', controller='error') # Home mc('/', controller='home', action='index') # very custom mc('/{id}-{title}', controller='page', action='view') mc('/cms', controller='mgmt', action='index') mc('/cms/{action}', controller='mgmt') mc('/cms/{action}/{id}', controller='mgmt') mc('/nieuws', controller='news', action='list') mc('/nieuws/{id}/{title}', controller='news', action='view') mc('/resource/{action}/{id}/{name}', controller='fetch') # Default fallbacks (cms, other pages) mc('/{controller}', action='index') mc('/{controller}/{action}') mc('/{controller}/{action}/{id}') return map
def make_map(config): """Create, configure and return the routes Mapper""" mapper = Mapper() connect = mapper.connect # For backwards compatibility with 0.9.7. mapper.explicit = False # Note that all of these paths are relative to the base path, /manager. connect('/', controller='services', action='index') connect('/home', controller='home', action='index') connect('/home/state', controller='home', action='state') connect('/auth/signin', controller='auth', action='signin') connect('/auth/signin_form', controller='auth', action='signin_form') connect('/auth/signout', controller='auth', action='signout') connect('/services', controller='services', action='listServices') connect('/services/removeService/{id}', controller='services', action='removeService') connect('/instances', controller='instances', action='index') connect('/instances/startInstance/{id}', controller='instances', action='startInstance') connect('/instances/stopInstance/{id}', controller='instances', action='stopInstance') connect('/instances/migrate/{id}', controller='instances', action='migrateInstance') connect('/instances/receiveMigratedSVMMetadata', controller='instances', action='receiveMigratedSVMMetadata') connect('/instances/receiveMigratedSVMDiskFile', controller='instances', action='receiveMigratedSVMDiskFile') connect('/instances/resumeMigratedSVM', controller='instances', action='resumeMigratedSVM') connect('/instances/getMigrationInfo/{id}', controller='instances', action='getMigrationInfo') connect('/instances/svmList', controller='instances', action='svmList') connect('add_service', '/service/add', controller='modify', action='index') connect('/service/createSVM', controller='modify', action='createSVM') connect('/service/saveNewSVM', controller='modify', action='saveNewSVM') connect('/service/openSVM/{id}', controller='modify', action='openSVM') connect('/service/edit/{id}', controller='modify', action='index') connect('/service/saveSVM', controller='modify', action='saveInstanceToRoot') connect('/service/getImageInfo', controller='modify', action='getImageInfo') connect('/apps', controller='apps', action='index') connect('/apps/list', controller='apps', action='list') connect('/apps/get', controller='apps', action='get_data') connect('/apps/add', controller='apps', action='add') connect('/apps/edit', controller='apps', action='edit') connect('/apps/remove', controller='apps', action='remove') connect('export_service', '/service/exportsvm/{sid}', controller='export', action='export_svm') connect('import_service', '/service/importsvm', controller='import', action='import') connect('list_devices', '/devices', controller='devices', action='list') connect('clear', '/devices/clear', controller='devices', action='clear') connect('bootrstrap', '/devices/bootstrap', controller='devices', action='bootstrap') connect('available_devices', '/devices/available', controller='pairing', action='available') connect('pair_device', '/devices/pair/{id}', controller='pairing', action='pair') connect('authorize_device', '/devices/authorize/{did}', controller='devices', action='authorize') connect('unpair_device', '/devices/unpair/{id}', controller='devices', action='unpair') connect('revoke_auth', '/devices/revoke/{id}', controller='devices', action='revoke') connect('reauthorize', '/devices/reauthorize/{id}', controller='devices', action='reauthorize') return mapper
def get_mapper(): global __mapper__ if not __mapper__: mapper = Mapper() for name, route, controller, action, module in rotas: mapper.connect(name, route, controller="%s.%s" % (module, controller), action=action) __mapper__ = mapper return __mapper__
def create_mapper(config, controller_scan=controller_scan): """Create, configure and return the routes Mapper""" map = Mapper( controller_scan=controller_scan, directory=config["pylons.paths"]["controllers"], always_scan=config["debug"] ) map.explicit = False map.minimization = True # TODO: Rework routes so we can set this to False return map
def _test_StreamingServer(): expected_id = 'test' headers = { #'TimeSeekRange.dlna.org': 'npt=30.000-', 'TimeSeekRange.dlna.org': 'npt=20.000-50.000', #'Range': 'bytes=5-', 'Connection': 'close', } duration = '00:01:00' content_length = 64 * 1024 interface = '192.168.0.103' class StreamingServerStub(ByteSeekMixin, TimeSeekMixin, StreamingServer): def get_content(self, id, environ): eq_(expected_id, id) #raise ValueError(repr(environ)) for k in headers: eq_(headers[k], environ['HTTP_' + k.upper()]) return ContentStub(content_length, 'video/mpeg', 'DLNA.ORG_PN=MPEG_PS_NTSC;DLNA.ORG_OP=11') from twisted.web import client class HTTPPageGetter(client.HTTPPageGetter): handleStatus_206 = lambda self: self.handleStatus_200() class HTTPClientFactory(client.HTTPClientFactory): protocol = HTTPPageGetter def getPageFactory(url, *args, **kwargs): scheme, host, port, path = client._parse(url) factory = HTTPClientFactory(url, *args, **kwargs) reactor.connectTCP(host, port, factory) return factory app = StreamingServerStub('test') mapper = Mapper() mapper.connect(':id', controller='mt', action='get') app = RoutesMiddleware(app, mapper) tpool = ThreadPool() tpool.start() resource = upnp.WSGIResource(reactor, tpool, app) port = reactor.listenTCP(0, server.Site(resource), interface=interface) port_num = port.socket.getsockname()[1] url = 'http://%s:%i/%s?duration=%s' % (interface, port_num, expected_id, duration) factory = getPageFactory(url, headers=headers) def check_result(contents): raise ValueError('expected: %d, actual: %d' % (content_length, len(contents))) #raise ValueError(repr(factory.response_headers)) eq_(content_length, len(contents)) factory.deferred.addCallback(check_result) reactor.callLater(5, reactor.stop) reactor.run()
def test_resources_with_collection_action(self): member_name = "message" collection_name = "messages" mapper = Mapper() mapper.resource(member_name, collection_name, collection={"rss": "GET"}) environ = {"REQUEST_METHOD":"GET"} match_dict = mapper.match("/messages/rss", environ) self.assertDictEqual(match_dict, {'action': u'rss', 'controller': u'messages'})
def test_resources_with_member_action(self): member_name = "message" collection_name = "messages" mapper = Mapper() mapper.resource(member_name, collection_name, member={'mark':'POST'}) environ = {"REQUEST_METHOD":"POST"} match_dict = mapper.match("/messages/123/mark", environ) self.assertDictEqual(match_dict, {'action': u'mark', 'controller': u'messages', 'id': u'123'})
def test_resources_with_path_prefix(self): member_name = "message" collection_name = "messages" mapper = Mapper() mapper.resource(member_name, collection_name, path_prefix="/category/{category_id}") environ = {"REQUEST_METHOD":"GET"} match_dict = mapper.match("/category/123/messages/456", environ) self.assertDictEqual(match_dict, {'action': u'show', 'controller': u'messages', 'category_id': u'123', 'id': u'456'})
def __init__(self): self.controller = controller() self.controller2 = controller2() m = Mapper() m.connect('blog', '/blog/{action}/{id}', controller=controller, conditions={'method': ['GET']}) m.connect('haha', '/haha/{action}/{id}', controller=controller2, conditions={'method': ['GET']}) self.router = middleware.RoutesMiddleware(self.dispatch, m)
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # Page section map.connect('/', controller='index', action='index') map.connect('/add', controller='page', action='add') map.connect('/selected', controller='page', action='selected') map.connect('/selected/', controller='page', action='selected') # Auth section map.connect('/register', controller='auth', action='register_post', conditions=dict(method=['POST'])) map.connect('/register', controller='auth', action='register') map.connect('/register/', controller='auth', action='register') map.connect('/login', controller='auth', action='login_post', conditions=dict(method=['POST'])) map.connect('/login', controller='auth', action='login') map.connect('/login/', controller='auth', action='login') map.connect('/logout', controller='auth', action='logout') #map.connect('/{controller}', action='index') map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') return map
def create_routes_router(uri_data): endpoint = Endpoint("routes") router = Mapper() # static routes for u in uri_data.get_static_uris(): router.connect(None, u, controller=endpoint) # zero variable template = uri_data.get_zero_var_uri(ParamFormat.ROUTES) router.connect(None, template, controller=endpoint) # one variable template = uri_data.get_one_var_uri(ParamFormat.ROUTES) router.connect(None, template, controller=endpoint) # two variables template = uri_data.get_two_var_uri(ParamFormat.ROUTES) router.connect(None, template, controller=endpoint) # three variables template = uri_data.get_three_var_uri(ParamFormat.ROUTES) router.connect(None, template, controller=endpoint) # done return router
def __init__(self, **config): self.config = config self.mapper = Mapper() self.registory = {} self._wsmanager = WebSocketManager() super().__init__()
def make_map(config): """Create, configure and return the routes Mapper""" rmap = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) rmap.minimization = False rmap.explicit = False from rhodecode.lib.utils import is_valid_repo from rhodecode.lib.utils import is_valid_repos_group def check_repo(environ, match_dict): """ check for valid repository for proper 404 handling :param environ: :param match_dict: """ from rhodecode.model.db import Repository repo_name = match_dict.get('repo_name') if match_dict.get('f_path'): #fix for multiple initial slashes that causes errors match_dict['f_path'] = match_dict['f_path'].lstrip('/') try: by_id = repo_name.split('_') if len(by_id) == 2 and by_id[1].isdigit() and by_id[0] == '': repo_name = Repository.get(by_id[1]).repo_name match_dict['repo_name'] = repo_name except Exception: pass return is_valid_repo(repo_name, config['base_path']) def check_group(environ, match_dict): """ check for valid repository group for proper 404 handling :param environ: :param match_dict: """ repos_group_name = match_dict.get('group_name') return is_valid_repos_group(repos_group_name, config['base_path']) def check_group_skip_path(environ, match_dict): """ check for valid repository group for proper 404 handling, but skips verification of existing path :param environ: :param match_dict: """ repos_group_name = match_dict.get('group_name') return is_valid_repos_group(repos_group_name, config['base_path'], skip_path_check=True) def check_user_group(environ, match_dict): """ check for valid user group for proper 404 handling :param environ: :param match_dict: """ return True def check_int(environ, match_dict): return match_dict.get('id').isdigit() # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved rmap.connect('/error/{action}', controller='error') rmap.connect('/error/{action}/{id}', controller='error') #========================================================================== # CUSTOM ROUTES HERE #========================================================================== #MAIN PAGE rmap.connect('home', '/', controller='home', action='index') rmap.connect('repo_switcher', '/repos', controller='home', action='repo_switcher') rmap.connect('branch_tag_switcher', '/branches-tags/{repo_name:.*?}', controller='home', action='branch_tag_switcher') rmap.connect('rst_help', "http://docutils.sourceforge.net/docs/user/rst/quickref.html", _static=True) rmap.connect('rhodecode_official', "http://rhodecode.org", _static=True) #ADMIN REPOSITORY REST ROUTES with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='admin/repos') as m: m.connect("repos", "/repos", action="create", conditions=dict(method=["POST"])) m.connect("repos", "/repos", action="index", conditions=dict(method=["GET"])) m.connect("formatted_repos", "/repos.{format}", action="index", conditions=dict(method=["GET"])) m.connect("new_repo", "/create_repository", action="create_repository", conditions=dict(method=["GET"])) m.connect("/repos/{repo_name:.*?}", action="update", conditions=dict(method=["PUT"], function=check_repo)) m.connect("/repos/{repo_name:.*?}", action="delete", conditions=dict(method=["DELETE"], function=check_repo)) m.connect("formatted_edit_repo", "/repos/{repo_name:.*?}.{format}/edit", action="edit", conditions=dict(method=["GET"], function=check_repo)) m.connect("repo", "/repos/{repo_name:.*?}", action="show", conditions=dict(method=["GET"], function=check_repo)) m.connect("formatted_repo", "/repos/{repo_name:.*?}.{format}", action="show", conditions=dict(method=["GET"], function=check_repo)) #add repo perm member m.connect('set_repo_perm_member', "/repos/{repo_name:.*?}/grant_perm", action="set_repo_perm_member", conditions=dict(method=["POST"], function=check_repo)) #ajax delete repo perm user m.connect('delete_repo_perm_member', "/repos/{repo_name:.*?}/revoke_perm", action="delete_repo_perm_member", conditions=dict(method=["DELETE"], function=check_repo)) #settings actions m.connect('repo_stats', "/repos_stats/{repo_name:.*?}", action="repo_stats", conditions=dict(method=["DELETE"], function=check_repo)) m.connect('repo_cache', "/repos_cache/{repo_name:.*?}", action="repo_cache", conditions=dict(method=["DELETE"], function=check_repo)) m.connect('repo_public_journal', "/repos_public_journal/{repo_name:.*?}", action="repo_public_journal", conditions=dict(method=["PUT"], function=check_repo)) m.connect('repo_pull', "/repo_pull/{repo_name:.*?}", action="repo_pull", conditions=dict(method=["PUT"], function=check_repo)) m.connect('repo_as_fork', "/repo_as_fork/{repo_name:.*?}", action="repo_as_fork", conditions=dict(method=["PUT"], function=check_repo)) m.connect('repo_locking', "/repo_locking/{repo_name:.*?}", action="repo_locking", conditions=dict(method=["PUT"], function=check_repo)) m.connect('toggle_locking', "/locking_toggle/{repo_name:.*?}", action="toggle_locking", conditions=dict(method=["GET"], function=check_repo)) #repo fields m.connect('create_repo_fields', "/repo_fields/{repo_name:.*?}/new", action="create_repo_field", conditions=dict(method=["PUT"], function=check_repo)) m.connect('delete_repo_fields', "/repo_fields/{repo_name:.*?}/{field_id}", action="delete_repo_field", conditions=dict(method=["DELETE"], function=check_repo)) with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='admin/repos_groups') as m: m.connect("repos_groups", "/repos_groups", action="create", conditions=dict(method=["POST"])) m.connect("repos_groups", "/repos_groups", action="index", conditions=dict(method=["GET"])) m.connect("formatted_repos_groups", "/repos_groups.{format}", action="index", conditions=dict(method=["GET"])) m.connect("new_repos_group", "/repos_groups/new", action="new", conditions=dict(method=["GET"])) m.connect("formatted_new_repos_group", "/repos_groups/new.{format}", action="new", conditions=dict(method=["GET"])) m.connect("update_repos_group", "/repos_groups/{group_name:.*?}", action="update", conditions=dict(method=["PUT"], function=check_group)) #add repo group perm member m.connect('set_repo_group_perm_member', "/repos_groups/{group_name:.*?}/grant_perm", action="set_repo_group_perm_member", conditions=dict(method=["POST"], function=check_group)) #ajax delete repo group perm m.connect('delete_repo_group_perm_member', "/repos_groups/{group_name:.*?}/revoke_perm", action="delete_repo_group_perm_member", conditions=dict(method=["DELETE"], function=check_group)) m.connect("delete_repos_group", "/repos_groups/{group_name:.*?}", action="delete", conditions=dict(method=["DELETE"], function=check_group_skip_path)) m.connect("edit_repos_group", "/repos_groups/{group_name:.*?}/edit", action="edit", conditions=dict(method=["GET"], function=check_group)) m.connect("formatted_edit_repos_group", "/repos_groups/{group_name:.*?}.{format}/edit", action="edit", conditions=dict(method=["GET"], function=check_group)) m.connect("repos_group", "/repos_groups/{group_name:.*?}", action="show", conditions=dict(method=["GET"], function=check_group)) m.connect("formatted_repos_group", "/repos_groups/{group_name:.*?}.{format}", action="show", conditions=dict(method=["GET"], function=check_group)) #ADMIN USER REST ROUTES with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='admin/users') as m: m.connect("users", "/users", action="create", conditions=dict(method=["POST"])) m.connect("users", "/users", action="index", conditions=dict(method=["GET"])) m.connect("formatted_users", "/users.{format}", action="index", conditions=dict(method=["GET"])) m.connect("new_user", "/users/new", action="new", conditions=dict(method=["GET"])) m.connect("formatted_new_user", "/users/new.{format}", action="new", conditions=dict(method=["GET"])) m.connect("update_user", "/users/{id}", action="update", conditions=dict(method=["PUT"])) m.connect("delete_user", "/users/{id}", action="delete", conditions=dict(method=["DELETE"])) m.connect("edit_user", "/users/{id}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("formatted_edit_user", "/users/{id}.{format}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("user", "/users/{id}", action="show", conditions=dict(method=["GET"])) m.connect("formatted_user", "/users/{id}.{format}", action="show", conditions=dict(method=["GET"])) #EXTRAS USER ROUTES m.connect("user_perm", "/users_perm/{id}", action="update_perm", conditions=dict(method=["PUT"])) m.connect("user_emails", "/users_emails/{id}", action="add_email", conditions=dict(method=["PUT"])) m.connect("user_emails_delete", "/users_emails/{id}", action="delete_email", conditions=dict(method=["DELETE"])) m.connect("user_ips", "/users_ips/{id}", action="add_ip", conditions=dict(method=["PUT"])) m.connect("user_ips_delete", "/users_ips/{id}", action="delete_ip", conditions=dict(method=["DELETE"])) #ADMIN USER GROUPS REST ROUTES with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='admin/users_groups') as m: m.connect("users_groups", "/users_groups", action="create", conditions=dict(method=["POST"])) m.connect("users_groups", "/users_groups", action="index", conditions=dict(method=["GET"])) m.connect("formatted_users_groups", "/users_groups.{format}", action="index", conditions=dict(method=["GET"])) m.connect("new_users_group", "/users_groups/new", action="new", conditions=dict(method=["GET"])) m.connect("formatted_new_users_group", "/users_groups/new.{format}", action="new", conditions=dict(method=["GET"])) m.connect("update_users_group", "/users_groups/{id}", action="update", conditions=dict(method=["PUT"])) m.connect("delete_users_group", "/users_groups/{id}", action="delete", conditions=dict(method=["DELETE"])) m.connect("edit_users_group", "/users_groups/{id}/edit", action="edit", conditions=dict(method=["GET"]), function=check_user_group) m.connect("formatted_edit_users_group", "/users_groups/{id}.{format}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("users_group", "/users_groups/{id}", action="show", conditions=dict(method=["GET"])) m.connect("formatted_users_group", "/users_groups/{id}.{format}", action="show", conditions=dict(method=["GET"])) #EXTRAS USER ROUTES # update m.connect("users_group_perm", "/users_groups/{id}/update_global_perm", action="update_perm", conditions=dict(method=["PUT"])) #add user group perm member m.connect('set_user_group_perm_member', "/users_groups/{id}/grant_perm", action="set_user_group_perm_member", conditions=dict(method=["POST"])) #ajax delete user group perm m.connect('delete_user_group_perm_member', "/users_groups/{id}/revoke_perm", action="delete_user_group_perm_member", conditions=dict(method=["DELETE"])) #ADMIN GROUP REST ROUTES rmap.resource('group', 'groups', controller='admin/groups', path_prefix=ADMIN_PREFIX) #ADMIN PERMISSIONS REST ROUTES rmap.resource('permission', 'permissions', controller='admin/permissions', path_prefix=ADMIN_PREFIX) #ADMIN DEFAULTS REST ROUTES rmap.resource('default', 'defaults', controller='admin/defaults', path_prefix=ADMIN_PREFIX) ##ADMIN LDAP SETTINGS rmap.connect('ldap_settings', '%s/ldap' % ADMIN_PREFIX, controller='admin/ldap_settings', action='ldap_settings', conditions=dict(method=["POST"])) rmap.connect('ldap_home', '%s/ldap' % ADMIN_PREFIX, controller='admin/ldap_settings') #ADMIN SETTINGS REST ROUTES with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='admin/settings') as m: m.connect("admin_settings", "/settings", action="create", conditions=dict(method=["POST"])) m.connect("admin_settings", "/settings", action="index", conditions=dict(method=["GET"])) m.connect("formatted_admin_settings", "/settings.{format}", action="index", conditions=dict(method=["GET"])) m.connect("admin_new_setting", "/settings/new", action="new", conditions=dict(method=["GET"])) m.connect("formatted_admin_new_setting", "/settings/new.{format}", action="new", conditions=dict(method=["GET"])) m.connect("/settings/{setting_id}", action="update", conditions=dict(method=["PUT"])) m.connect("/settings/{setting_id}", action="delete", conditions=dict(method=["DELETE"])) m.connect("admin_edit_setting", "/settings/{setting_id}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("formatted_admin_edit_setting", "/settings/{setting_id}.{format}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("admin_setting", "/settings/{setting_id}", action="show", conditions=dict(method=["GET"])) m.connect("formatted_admin_setting", "/settings/{setting_id}.{format}", action="show", conditions=dict(method=["GET"])) m.connect("admin_settings_my_account", "/my_account", action="my_account", conditions=dict(method=["GET"])) m.connect("admin_settings_my_account_update", "/my_account_update", action="my_account_update", conditions=dict(method=["PUT"])) m.connect("admin_settings_my_repos", "/my_account/repos", action="my_account_my_repos", conditions=dict(method=["GET"])) m.connect("admin_settings_my_pullrequests", "/my_account/pull_requests", action="my_account_my_pullrequests", conditions=dict(method=["GET"])) #NOTIFICATION REST ROUTES with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='admin/notifications') as m: m.connect("notifications", "/notifications", action="create", conditions=dict(method=["POST"])) m.connect("notifications", "/notifications", action="index", conditions=dict(method=["GET"])) m.connect("notifications_mark_all_read", "/notifications/mark_all_read", action="mark_all_read", conditions=dict(method=["GET"])) m.connect("formatted_notifications", "/notifications.{format}", action="index", conditions=dict(method=["GET"])) m.connect("new_notification", "/notifications/new", action="new", conditions=dict(method=["GET"])) m.connect("formatted_new_notification", "/notifications/new.{format}", action="new", conditions=dict(method=["GET"])) m.connect("/notifications/{notification_id}", action="update", conditions=dict(method=["PUT"])) m.connect("/notifications/{notification_id}", action="delete", conditions=dict(method=["DELETE"])) m.connect("edit_notification", "/notifications/{notification_id}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("formatted_edit_notification", "/notifications/{notification_id}.{format}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("notification", "/notifications/{notification_id}", action="show", conditions=dict(method=["GET"])) m.connect("formatted_notification", "/notifications/{notification_id}.{format}", action="show", conditions=dict(method=["GET"])) #ADMIN GIST with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='admin/gists') as m: m.connect("gists", "/gists", action="create", conditions=dict(method=["POST"])) m.connect("gists", "/gists", action="index", conditions=dict(method=["GET"])) m.connect("new_gist", "/gists/new", action="new", conditions=dict(method=["GET"])) m.connect("formatted_new_gist", "/gists/new.{format}", action="new", conditions=dict(method=["GET"])) m.connect("formatted_gists", "/gists.{format}", action="index", conditions=dict(method=["GET"])) m.connect("/gists/{gist_id}", action="update", conditions=dict(method=["PUT"])) m.connect("/gists/{gist_id}", action="delete", conditions=dict(method=["DELETE"])) m.connect("edit_gist", "/gists/{gist_id}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("formatted_edit_gist", "/gists/{gist_id}/{format}/edit", action="edit", conditions=dict(method=["GET"])) m.connect("gist", "/gists/{gist_id}", action="show", conditions=dict(method=["GET"])) m.connect("formatted_gist", "/gists/{gist_id}/{format}", action="show", conditions=dict(method=["GET"])) m.connect("formatted_gist_file", "/gists/{gist_id}/{format}/{revision}/{f_path:.*}", action="show", conditions=dict(method=["GET"])) #ADMIN MAIN PAGES with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='admin/admin') as m: m.connect('admin_home', '', action='index') m.connect('admin_add_repo', '/add_repo/{new_repo:[a-z0-9\. _-]*}', action='add_repo') #========================================================================== # API V2 #========================================================================== with rmap.submapper(path_prefix=ADMIN_PREFIX, controller='api/api') as m: m.connect('api', '/api') #USER JOURNAL rmap.connect('journal', '%s/journal' % ADMIN_PREFIX, controller='journal', action='index') rmap.connect('journal_rss', '%s/journal/rss' % ADMIN_PREFIX, controller='journal', action='journal_rss') rmap.connect('journal_atom', '%s/journal/atom' % ADMIN_PREFIX, controller='journal', action='journal_atom') rmap.connect('public_journal', '%s/public_journal' % ADMIN_PREFIX, controller='journal', action="public_journal") rmap.connect('public_journal_rss', '%s/public_journal/rss' % ADMIN_PREFIX, controller='journal', action="public_journal_rss") rmap.connect('public_journal_rss_old', '%s/public_journal_rss' % ADMIN_PREFIX, controller='journal', action="public_journal_rss") rmap.connect('public_journal_atom', '%s/public_journal/atom' % ADMIN_PREFIX, controller='journal', action="public_journal_atom") rmap.connect('public_journal_atom_old', '%s/public_journal_atom' % ADMIN_PREFIX, controller='journal', action="public_journal_atom") rmap.connect('toggle_following', '%s/toggle_following' % ADMIN_PREFIX, controller='journal', action='toggle_following', conditions=dict(method=["POST"])) #SEARCH rmap.connect('search', '%s/search' % ADMIN_PREFIX, controller='search',) rmap.connect('search_repo_admin', '%s/search/{repo_name:.*}' % ADMIN_PREFIX, controller='search', conditions=dict(function=check_repo)) rmap.connect('search_repo', '/{repo_name:.*?}/search', controller='search', conditions=dict(function=check_repo), ) #LOGIN/LOGOUT/REGISTER/SIGN IN rmap.connect('login_home', '%s/login' % ADMIN_PREFIX, controller='login') rmap.connect('logout_home', '%s/logout' % ADMIN_PREFIX, controller='login', action='logout') rmap.connect('register', '%s/register' % ADMIN_PREFIX, controller='login', action='register') rmap.connect('reset_password', '%s/password_reset' % ADMIN_PREFIX, controller='login', action='password_reset') rmap.connect('reset_password_confirmation', '%s/password_reset_confirmation' % ADMIN_PREFIX, controller='login', action='password_reset_confirmation') #FEEDS rmap.connect('rss_feed_home', '/{repo_name:.*?}/feed/rss', controller='feed', action='rss', conditions=dict(function=check_repo)) rmap.connect('atom_feed_home', '/{repo_name:.*?}/feed/atom', controller='feed', action='atom', conditions=dict(function=check_repo)) #========================================================================== # REPOSITORY ROUTES #========================================================================== rmap.connect('summary_home', '/{repo_name:.*?}', controller='summary', conditions=dict(function=check_repo)) rmap.connect('repo_size', '/{repo_name:.*?}/repo_size', controller='summary', action='repo_size', conditions=dict(function=check_repo)) rmap.connect('repos_group_home', '/{group_name:.*}', controller='admin/repos_groups', action="show_by_name", conditions=dict(function=check_group)) rmap.connect('changeset_home', '/{repo_name:.*?}/changeset/{revision}', controller='changeset', revision='tip', conditions=dict(function=check_repo)) # no longer user, but kept for routes to work rmap.connect("_edit_repo", "/{repo_name:.*?}/edit", controller='admin/repos', action="edit", conditions=dict(method=["GET"], function=check_repo) ) rmap.connect("edit_repo", "/{repo_name:.*?}/settings", controller='admin/repos', action="edit", conditions=dict(method=["GET"], function=check_repo) ) #still working url for backward compat. rmap.connect('raw_changeset_home_depraced', '/{repo_name:.*?}/raw-changeset/{revision}', controller='changeset', action='changeset_raw', revision='tip', conditions=dict(function=check_repo)) ## new URLs rmap.connect('changeset_raw_home', '/{repo_name:.*?}/changeset-diff/{revision}', controller='changeset', action='changeset_raw', revision='tip', conditions=dict(function=check_repo)) rmap.connect('changeset_patch_home', '/{repo_name:.*?}/changeset-patch/{revision}', controller='changeset', action='changeset_patch', revision='tip', conditions=dict(function=check_repo)) rmap.connect('changeset_download_home', '/{repo_name:.*?}/changeset-download/{revision}', controller='changeset', action='changeset_download', revision='tip', conditions=dict(function=check_repo)) rmap.connect('changeset_comment', '/{repo_name:.*?}/changeset/{revision}/comment', controller='changeset', revision='tip', action='comment', conditions=dict(function=check_repo)) rmap.connect('changeset_comment_preview', '/{repo_name:.*?}/changeset/comment/preview', controller='changeset', action='preview_comment', conditions=dict(function=check_repo, method=["POST"])) rmap.connect('changeset_comment_delete', '/{repo_name:.*?}/changeset/comment/{comment_id}/delete', controller='changeset', action='delete_comment', conditions=dict(function=check_repo, method=["DELETE"])) rmap.connect('changeset_info', '/changeset_info/{repo_name:.*?}/{revision}', controller='changeset', action='changeset_info') rmap.connect('compare_url', '/{repo_name:.*?}/compare/{org_ref_type}@{org_ref:.*?}...{other_ref_type}@{other_ref:.*?}', controller='compare', action='index', conditions=dict(function=check_repo), requirements=dict( org_ref_type='(branch|book|tag|rev|__other_ref_type__)', other_ref_type='(branch|book|tag|rev|__org_ref_type__)') ) rmap.connect('pullrequest_home', '/{repo_name:.*?}/pull-request/new', controller='pullrequests', action='index', conditions=dict(function=check_repo, method=["GET"])) rmap.connect('pullrequest', '/{repo_name:.*?}/pull-request/new', controller='pullrequests', action='create', conditions=dict(function=check_repo, method=["POST"])) rmap.connect('pullrequest_show', '/{repo_name:.*?}/pull-request/{pull_request_id}', controller='pullrequests', action='show', conditions=dict(function=check_repo, method=["GET"])) rmap.connect('pullrequest_update', '/{repo_name:.*?}/pull-request/{pull_request_id}', controller='pullrequests', action='update', conditions=dict(function=check_repo, method=["PUT"])) rmap.connect('pullrequest_delete', '/{repo_name:.*?}/pull-request/{pull_request_id}', controller='pullrequests', action='delete', conditions=dict(function=check_repo, method=["DELETE"])) rmap.connect('pullrequest_show_all', '/{repo_name:.*?}/pull-request', controller='pullrequests', action='show_all', conditions=dict(function=check_repo, method=["GET"])) rmap.connect('pullrequest_comment', '/{repo_name:.*?}/pull-request-comment/{pull_request_id}', controller='pullrequests', action='comment', conditions=dict(function=check_repo, method=["POST"])) rmap.connect('pullrequest_comment_delete', '/{repo_name:.*?}/pull-request-comment/{comment_id}/delete', controller='pullrequests', action='delete_comment', conditions=dict(function=check_repo, method=["DELETE"])) rmap.connect('summary_home_summary', '/{repo_name:.*?}/summary', controller='summary', conditions=dict(function=check_repo)) rmap.connect('branches_home', '/{repo_name:.*?}/branches', controller='branches', conditions=dict(function=check_repo)) rmap.connect('tags_home', '/{repo_name:.*?}/tags', controller='tags', conditions=dict(function=check_repo)) rmap.connect('bookmarks_home', '/{repo_name:.*?}/bookmarks', controller='bookmarks', conditions=dict(function=check_repo)) rmap.connect('changelog_home', '/{repo_name:.*?}/changelog', controller='changelog', conditions=dict(function=check_repo)) rmap.connect('changelog_summary_home', '/{repo_name:.*?}/changelog_summary', controller='changelog', action='changelog_summary', conditions=dict(function=check_repo)) rmap.connect('changelog_file_home', '/{repo_name:.*?}/changelog/{revision}/{f_path:.*}', controller='changelog', f_path=None, conditions=dict(function=check_repo)) rmap.connect('changelog_details', '/{repo_name:.*?}/changelog_details/{cs}', controller='changelog', action='changelog_details', conditions=dict(function=check_repo)) rmap.connect('files_home', '/{repo_name:.*?}/files/{revision}/{f_path:.*}', controller='files', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_home_nopath', '/{repo_name:.*?}/files/{revision}', controller='files', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_history_home', '/{repo_name:.*?}/history/{revision}/{f_path:.*}', controller='files', action='history', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_diff_home', '/{repo_name:.*?}/diff/{f_path:.*}', controller='files', action='diff', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_diff_2way_home', '/{repo_name:.*?}/diff-2way/{f_path:.*}', controller='files', action='diff_2way', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_rawfile_home', '/{repo_name:.*?}/rawfile/{revision}/{f_path:.*}', controller='files', action='rawfile', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_raw_home', '/{repo_name:.*?}/raw/{revision}/{f_path:.*}', controller='files', action='raw', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_annotate_home', '/{repo_name:.*?}/annotate/{revision}/{f_path:.*}', controller='files', action='index', revision='tip', f_path='', annotate=True, conditions=dict(function=check_repo)) rmap.connect('files_edit_home', '/{repo_name:.*?}/edit/{revision}/{f_path:.*}', controller='files', action='edit', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_add_home', '/{repo_name:.*?}/add/{revision}/{f_path:.*}', controller='files', action='add', revision='tip', f_path='', conditions=dict(function=check_repo)) rmap.connect('files_archive_home', '/{repo_name:.*?}/archive/{fname}', controller='files', action='archivefile', conditions=dict(function=check_repo)) rmap.connect('files_nodelist_home', '/{repo_name:.*?}/nodelist/{revision}/{f_path:.*}', controller='files', action='nodelist', conditions=dict(function=check_repo)) rmap.connect('repo_fork_create_home', '/{repo_name:.*?}/fork', controller='forks', action='fork_create', conditions=dict(function=check_repo, method=["POST"])) rmap.connect('repo_fork_home', '/{repo_name:.*?}/fork', controller='forks', action='fork', conditions=dict(function=check_repo)) rmap.connect('repo_forks_home', '/{repo_name:.*?}/forks', controller='forks', action='forks', conditions=dict(function=check_repo)) rmap.connect('repo_followers_home', '/{repo_name:.*?}/followers', controller='followers', action='followers', conditions=dict(function=check_repo)) return rmap
import traceback from routes import Mapper from urllib.parse import urlparse, parse_qs getMap = Mapper() postMap = Mapper() putMap = Mapper() deleteMap = Mapper() def executeController(map, requestHandler): try: parsedPath = urlparse(requestHandler.path) contentLength = int(requestHandler.headers.get('content-length', 0)) body = requestHandler.rfile.read(contentLength).decode('utf-8') result = map.match(parsedPath.path) if (result == None): return None function = result['controller'] request = Request( args = result, query = parse_qs(parsedPath.query), headers = requestHandler.headers, body = body ) return function(request) except BaseException:
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # CUSTOM ROUTES HERE map.connect('/map', controller="uifunc", action="index") map.connect('/about', controller="uifunc", action="about") map.connect('/about/goals', controller="uifunc", action="goals") map.connect('/docs', controller="uifunc", action="userDocs") map.connect('/docs/developer', controller="uifunc", action="devDocs") map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') return map
def __init__(self): self.mapper = Mapper() self.add_routes() self.router = middleware.RoutesMiddleware(self._dispatch, self.mapper)
def __init__(self): self._loop_control = False self._mapper = Mapper()
def make_map(): map = Mapper() mc = map.connect for plugin in reversed(config['r2.plugins']): plugin.add_routes(mc) mc('/admin/', controller='awards') mc('/login', controller='forms', action='login') mc('/register', controller='forms', action='register') mc('/logout', controller='forms', action='logout') mc('/verify', controller='forms', action='verify') mc('/adminon', controller='forms', action='adminon') mc('/adminoff', controller='forms', action='adminoff') mc('/submit', controller='front', action='submit') mc('/over18', controller='post', action='over18') mc('/search', controller='front', action='search') mc('/rules', controller='front', action='rules') mc('/sup', controller='front', action='sup') mc('/traffic', controller='front', action='site_traffic') mc('/traffic/languages/:langcode', controller='front', action='lang_traffic', langcode='') mc('/traffic/adverts/:code', controller='front', action='advert_traffic', code='') mc('/traffic/subreddits/report', controller='front', action='subreddit_traffic_report') mc('/account-activity', controller='front', action='account_activity') mc('/about/message/:where', controller='message', action='listing') mc('/about/log', controller='front', action='moderationlog') mc('/about/sidebar', controller='front', action='sidebar') mc('/about', controller='front', action='about') mc('/about/flair', controller='front', action='flairlisting') mc('/about/:location', controller='front', action='spamlisting', requirements=dict(location='reports|spam|modqueue|unmoderated')) mc('/about/:location', controller='front', action='editreddit', location='about') mc('/subreddits/create', controller='front', action='newreddit') mc('/subreddits/search', controller='front', action='search_reddits') mc('/subreddits/login', controller='forms', action='login') mc('/subreddits/:where', controller='reddits', action='listing', where='popular', requirements=dict(where="popular|new|banned")) mc('/subreddits/mine/:where', controller='myreddits', action='listing', where='subscriber', requirements=dict(where='subscriber|contributor|moderator')) # These routes are kept for backwards-compatibility reasons # Using the above /subreddits/ ones instead is preferable mc('/reddits/create', controller='front', action='newreddit') mc('/reddits/search', controller='front', action='search_reddits') mc('/reddits/login', controller='forms', action='login') mc('/reddits/:where', controller='reddits', action='listing', where='popular', requirements=dict(where="popular|new|banned")) mc('/reddits/mine/:where', controller='myreddits', action='listing', where='subscriber', requirements=dict(where='subscriber|contributor|moderator')) mc('/buttons', controller='buttons', action='button_demo_page') #/button.js and buttonlite.js - the embeds mc('/button', controller='buttons', action='button_embed') mc('/buttonlite', controller='buttons', action='button_lite') mc('/widget', controller='buttons', action='widget_demo_page') mc('/bookmarklets', controller='buttons', action='bookmarklets') mc('/awards', controller='front', action='awards') mc('/awards/confirm/:code', controller='front', action='confirm_award_claim') mc('/awards/claim/:code', controller='front', action='claim_award') mc('/awards/received', controller='front', action='received_award') mc('/i18n', controller='redirect', action='redirect', dest='http://www.reddit.com/r/i18n') mc('/feedback', controller='feedback', action='feedback') mc('/ad_inq', controller='feedback', action='ad_inq') mc('/admin/awards', controller='awards') mc('/admin/awards/:awardcn/:action', controller='awards', requirements=dict(action="give|winners")) mc('/admin/errors', controller='errorlog') mc('/user/:username/about', controller='user', action='about', where='overview') mc('/user/:username/:where', controller='user', action='listing', where='overview') mc('/u/:username', controller='redirect', action='user_redirect') # preserve timereddit URLs from 4/1/2012 mc('/t/:timereddit', controller='redirect', action='timereddit_redirect') mc('/t/:timereddit/*rest', controller='redirect', action='timereddit_redirect') mc('/prefs/:location', controller='forms', action='prefs', location='options') mc('/info/0:article/*rest', controller='front', action='oldinfo', dest='comments', type='ancient') mc('/info/:article/:dest/:comment', controller='front', action='oldinfo', type='old', dest='comments', comment=None) mc("/comments/gilded", controller="redirect", action="gilded_comments", conditions={"function": not_in_sr}) mc("/comments/gilded", action="listing", controller="gilded") mc('/related/:article/:title', controller='front', action='related', title=None) mc('/details/:article/:title', controller='front', action='details', title=None) mc('/traffic/:link/:campaign', controller='front', action='traffic', campaign=None) mc('/comments/:article/:title/:comment', controller='front', action='comments', title=None, comment=None) mc('/duplicates/:article/:title', controller='front', action='duplicates', title=None) mc('/mail/optout', controller='forms', action='optout') mc('/mail/optin', controller='forms', action='optin') mc('/stylesheet', controller='front', action='stylesheet') mc('/frame', controller='front', action='frame') mc('/framebuster/:blah', controller='front', action='framebuster') mc('/framebuster/:what/:blah', controller='front', action='framebuster') mc('/admin/promoted', controller='promote', action='admin') mc('/promoted/edit_promo/:link', controller='promote', action='edit_promo') mc( '/promoted/edit_promo_cpm/:link', # development only controller='promote', action='edit_promo_cpm') mc( '/promoted/edit_promo/pc/:campaign', controller='promote', # admin only action='edit_promo_campaign') mc('/promoted/pay/:link/:campaign', controller='promote', action='pay') mc('/promoted/graph', controller='promote', action='graph') mc('/promoted/admin/graph', controller='promote', action='admingraph') mc('/promoted/inventory/:sr_name', controller='promote', action='inventory') mc('/promoted/:action', controller='promote', requirements=dict(action="edit_promo|new_promo|roadblock")) mc('/promoted/report', controller='promote', action='report') mc('/promoted/:sort/:sr', controller='promote', action='listing', requirements=dict(sort='live_promos')) mc('/promoted/:sort', controller='promote', action="listing") mc('/promoted/', controller='promoted', action="listing", sort="") mc('/health', controller='health', action='health') mc('/health/ads', controller='health', action='promohealth') mc('/', controller='hot', action='listing') mc('/:controller', action='listing', requirements=dict(controller="hot|new|rising|randomrising|comments")) mc('/saved', controller='user', action='saved_redirect') mc('/by_id/:names', controller='byId', action='listing') mc('/:sort', controller='browse', sort='top', action='listing', requirements=dict(sort='top|controversial')) mc('/message/compose', controller='message', action='compose') mc('/message/messages/:mid', controller='message', action='listing', where="messages") mc('/message/:where', controller='message', action='listing') mc('/message/moderator/:subwhere', controller='message', action='listing', where='moderator') mc('/thanks', controller='forms', action="claim", secret='') mc('/thanks/:secret', controller='forms', action="claim") mc('/gold', controller='forms', action="gold") mc('/gold/creditgild/:passthrough', controller='forms', action='creditgild') mc('/gold/about', controller='front', action='gold_info') mc('/gold/thanks', controller='front', action='goldthanks') mc('/password', controller='forms', action="password") mc('/:action', controller='front', requirements=dict(action="random|framebuster|selfserviceoatmeal")) mc('/:action', controller='embed', requirements=dict(action="blog")) mc('/help/gold', controller='redirect', action='redirect', dest='/gold/about') mc('/help/:page', controller='policies', action='policy_page', conditions={'function': not_in_sr}, requirements={'page': 'privacypolicy|useragreement'}) mc('/wiki/create/*page', controller='wiki', action='wiki_create') mc('/wiki/edit/*page', controller='wiki', action='wiki_revise') mc('/wiki/revisions', controller='wiki', action='wiki_recent') mc('/wiki/revisions/*page', controller='wiki', action='wiki_revisions') mc('/wiki/settings/*page', controller='wiki', action='wiki_settings') mc('/wiki/discussions/*page', controller='wiki', action='wiki_discussions') mc('/wiki/pages', controller='wiki', action='wiki_listing') mc('/api/wiki/create', controller='wikiapi', action='wiki_create') mc('/api/wiki/edit', controller='wikiapi', action='wiki_edit') mc('/api/wiki/hide', controller='wikiapi', action='wiki_revision_hide') mc('/api/wiki/revert', controller='wikiapi', action='wiki_revision_revert') mc('/api/wiki/alloweditor/:act', controller='wikiapi', requirements=dict(act="del|add"), action='wiki_allow_editor') mc('/wiki/*page', controller='wiki', action='wiki_page') mc('/wiki/', controller='wiki', action='wiki_page') mc('/:action', controller='wiki', requirements=dict(action="help|faq")) mc('/help/*page', controller='wiki', action='wiki_redirect') mc('/w/*page', controller='wiki', action='wiki_redirect') mc('/goto', controller='toolbar', action='goto') mc('/tb/:id', controller='toolbar', action='tb') mc('/toolbar/:action', controller='toolbar', requirements=dict(action="toolbar|inner|login")) mc('/toolbar/comments/:id', controller='toolbar', action='comments') mc('/c/:comment_id', controller='front', action='comment_by_id') mc('/s/*rest', controller='toolbar', action='s') # additional toolbar-related rules just above the catchall mc('/d/:what', controller='api', action='bookmarklet') mc('/resetpassword/:key', controller='forms', action='resetpassword') mc('/verification/:key', controller='forms', action='verify_email') mc('/resetpassword', controller='forms', action='resetpassword') mc('/post/:action/:url_user', controller='post', requirements=dict(action="login|reg")) mc('/post/:action', controller='post', requirements=dict(action="options|over18|unlogged_options|optout" "|optin|login|reg")) mc('/api', controller='redirect', action='redirect', dest='/dev/api') mc('/api/distinguish/:how', controller='api', action="distinguish") # wherever this is, google has to agree. mc('/api/gcheckout', controller='ipn', action='gcheckout') mc('/api/spendcreddits', controller='ipn', action="spendcreddits") mc('/api/stripecharge/gold', controller='stripe', action='goldcharge') mc('/api/stripewebhook/gold/:secret', controller='stripe', action='goldwebhook') mc('/api/coinbasewebhook/gold/:secret', controller='coinbase', action='goldwebhook') mc('/api/rgwebhook/gold/:secret', controller='redditgifts', action='goldwebhook') mc('/api/ipn/:secret', controller='ipn', action='ipn') mc('/ipn/:secret', controller='ipn', action='ipn') mc('/api/:action/:url_user', controller='api', requirements=dict(action="login|register")) mc('/api/gadget/click/:ids', controller='api', action='gadget', type='click') mc('/api/gadget/:type', controller='api', action='gadget') mc('/api/:action', controller='promote', requirements=dict(action=("promote|unpromote|edit_promo|link_thumb|" "freebie|promote_note|update_pay|refund|" "traffic_viewer|rm_traffic_viewer|" "edit_campaign|delete_campaign|meta_promo|" "add_roadblock|rm_roadblock"))) mc('/api/:action', controller='apiminimal', requirements=dict(action="new_captcha")) mc('/api/:action', controller='api') mc("/api/v1/:action", controller="oauth2frontend", requirements=dict(action="authorize")) mc("/api/v1/:action", controller="oauth2access", requirements=dict(action="access_token")) mc("/api/v1/:action", controller="apiv1") mc('/dev', controller='redirect', action='redirect', dest='/dev/api') mc('/dev/api', controller='apidocs', action='docs') mc('/dev/api/:mode', controller='apidocs', action='docs', requirements=dict(mode="oauth")) mc("/button_info", controller="api", action="info", limit=1) mc('/captcha/:iden', controller='captcha', action='captchaimg') mc('/mediaembed/:link', controller="mediaembed", action="mediaembed") mc('/doquery', controller='query', action='doquery') mc('/code', controller='redirect', action='redirect', dest='http://github.com/reddit/') mc('/socialite', controller='redirect', action='redirect', dest='https://addons.mozilla.org/firefox/addon/socialite/') mc('/mobile', controller='redirect', action='redirect', dest='http://m.reddit.com/') mc('/authorize_embed', controller='front', action='authorize_embed') # Used for showing ads mc("/ads/", controller="ad", action="ad") mc("/try", controller="forms", action="try_compact") # This route handles displaying the error page and # graphics used in the 404/500 # error pages. It should likely stay at the top # to ensure that the error page is # displayed properly. mc('/error/document/:id', controller='error', action="document") # these should be near the buttom, because they should only kick # in if everything else fails. It's the attempted catch-all # reddit.com/http://... and reddit.com/34fr, but these redirect to # the less-guessy versions at /s/ and /tb/ mc('/:linkoid', controller='toolbar', action='linkoid', requirements=dict(linkoid='[0-9a-z]{1,6}')) mc('/:urloid', controller='toolbar', action='urloid', requirements=dict(urloid=r'(\w+\.\w{2,}|https?).*')) mc("/*url", controller='front', action='catchall') return map
def make_map(): """Create, configure and return the routes Mapper""" # import controllers here rather than at root level because # pylons config is initialised by this point. # Helpers to reduce code clutter GET = dict(method=['GET']) PUT = dict(method=['PUT']) POST = dict(method=['POST']) DELETE = dict(method=['DELETE']) GET_POST = dict(method=['GET', 'POST']) PUT_POST = dict(method=['PUT', 'POST']) PUT_POST_DELETE = dict(method=['PUT', 'POST', 'DELETE']) OPTIONS = dict(method=['OPTIONS']) from ckan.lib.plugins import register_package_plugins from ckan.lib.plugins import register_group_plugins map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = True # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved. map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') map.connect('*url', controller='home', action='cors_options', conditions=OPTIONS) # CUSTOM ROUTES HERE for plugin in routing_plugins: map = plugin.before_map(map) map.connect('home', '/', controller='home', action='index') map.connect('about', '/about', controller='home', action='about') # CKAN API versioned. register_list = [ 'package', 'dataset', 'resource', 'tag', 'group', 'related', 'revision', 'licenses', 'rating', 'user', 'activity' ] register_list_str = '|'.join(register_list) # /api ver 3 or none with SubMapper(map, controller='api', path_prefix='/api{ver:/3|}', ver='/3') as m: m.connect('/action/{logic_function}', action='action', conditions=GET_POST) # /api ver 1, 2, 3 or none with SubMapper(map, controller='api', path_prefix='/api{ver:/1|/2|/3|}', ver='/1') as m: m.connect('', action='get_api') m.connect('/search/{register}', action='search') # /api ver 1, 2 or none with SubMapper(map, controller='api', path_prefix='/api{ver:/1|/2|}', ver='/1') as m: m.connect('/tag_counts', action='tag_counts') m.connect('/rest', action='index') m.connect('/qos/throughput/', action='throughput', conditions=GET) # /api/rest ver 1, 2 or none with SubMapper(map, controller='api', path_prefix='/api{ver:/1|/2|}', ver='/1', requirements=dict(register=register_list_str)) as m: m.connect('/rest/{register}', action='list', conditions=GET) m.connect('/rest/{register}', action='create', conditions=POST) m.connect('/rest/{register}/{id}', action='show', conditions=GET) m.connect('/rest/{register}/{id}', action='update', conditions=PUT) m.connect('/rest/{register}/{id}', action='update', conditions=POST) m.connect('/rest/{register}/{id}', action='delete', conditions=DELETE) m.connect('/rest/{register}/{id}/:subregister', action='list', conditions=GET) m.connect('/rest/{register}/{id}/:subregister', action='create', conditions=POST) m.connect('/rest/{register}/{id}/:subregister/{id2}', action='create', conditions=POST) m.connect('/rest/{register}/{id}/:subregister/{id2}', action='show', conditions=GET) m.connect('/rest/{register}/{id}/:subregister/{id2}', action='update', conditions=PUT) m.connect('/rest/{register}/{id}/:subregister/{id2}', action='delete', conditions=DELETE) # /api/util ver 1, 2 or none with SubMapper(map, controller='api', path_prefix='/api{ver:/1|/2|}', ver='/1') as m: m.connect('/util/user/autocomplete', action='user_autocomplete') m.connect('/util/is_slug_valid', action='is_slug_valid', conditions=GET) m.connect('/util/dataset/autocomplete', action='dataset_autocomplete', conditions=GET) m.connect('/util/tag/autocomplete', action='tag_autocomplete', conditions=GET) m.connect('/util/resource/format_autocomplete', action='format_autocomplete', conditions=GET) m.connect('/util/resource/format_icon', action='format_icon', conditions=GET) m.connect('/util/group/autocomplete', action='group_autocomplete') m.connect('/util/markdown', action='markdown') m.connect('/util/dataset/munge_name', action='munge_package_name') m.connect('/util/dataset/munge_title_to_name', action='munge_title_to_package_name') m.connect('/util/tag/munge', action='munge_tag') m.connect('/util/status', action='status') m.connect('/util/snippet/{snippet_path:.*}', action='snippet') m.connect('/i18n/{lang}', action='i18n_js_translations') ########### ## /END API ########### ## Webstore if config.get('ckan.datastore.enabled', False): with SubMapper(map, controller='datastore') as m: m.connect('datastore_read', '/api/data/{id}{url:(/.*)?}', action='read', url='', conditions=GET) m.connect('datastore_write', '/api/data/{id}{url:(/.*)?}', action='write', url='', conditions=PUT_POST_DELETE) m.connect('datastore_read_shortcut', '/dataset/{dataset}/resource/{id}/api{url:(/.*)?}', action='read', url='', conditions=GET) m.connect('datastore_write_shortcut', '/dataset/{dataset}/resource/{id}/api{url:(/.*)?}', action='write', url='', conditions=PUT_POST_DELETE) map.redirect('/packages', '/dataset') map.redirect('/packages/{url:.*}', '/dataset/{url}') map.redirect('/package', '/dataset') map.redirect('/package/{url:.*}', '/dataset/{url}') ##to get back formalchemy uncomment these lines ##map.connect('/package/new', controller='package_formalchemy', action='new') ##map.connect('/package/edit/{id}', controller='package_formalchemy', action='edit') with SubMapper(map, controller='related') as m: m.connect('related_new', '/dataset/{id}/related/new', action='new') m.connect('related_edit', '/dataset/{id}/related/edit/{related_id}', action='edit') m.connect('related_delete', '/dataset/{id}/related/delete/{related_id}', action='delete') m.connect('related_list', '/dataset/{id}/related', action='list') m.connect('related_read', '/apps/{id}', action='read') m.connect('related_dashboard', '/apps', action='dashboard') with SubMapper(map, controller='package') as m: m.connect('/dataset', action='search') m.connect( '/dataset/{action}', requirements=dict( action='|'.join(['list', 'new', 'autocomplete', 'search']))) m.connect('/dataset/{action}/{id}/{revision}', action='read_ajax', requirements=dict(action='|'.join([ 'read', 'edit', 'authz', 'history', ]))) m.connect('/dataset/{action}/{id}', requirements=dict(action='|'.join([ 'edit', 'new_metadata', 'new_resource', 'authz', 'history', 'read_ajax', 'history_ajax', 'followers', 'delete', 'api_data', ]))) m.connect('/dataset/{id}.{format}', action='read') m.connect('/dataset/{id}', action='read') m.connect('/dataset/{id}/resource/{resource_id}', action='resource_read') m.connect('/dataset/{id}/resource_delete/{resource_id}', action='resource_delete') m.connect('/dataset/{id}/resource_edit/{resource_id}', action='resource_edit') m.connect('/dataset/{id}/resource/{resource_id}/download', action='resource_download') m.connect('/dataset/{id}/resource/{resource_id}/embed', action='resource_embedded_dataviewer') m.connect('/dataset/{id}/resource/{resource_id}/viewer', action='resource_embedded_dataviewer', width="960", height="800") m.connect( '/dataset/{id}/resource/{resource_id}/preview/{preview_type}', action='resource_datapreview') # group map.redirect('/groups', '/group') map.redirect('/groups/{url:.*}', '/group/{url}') ##to get back formalchemy uncomment these lines ##map.connect('/group/new', controller='group_formalchemy', action='new') ##map.connect('/group/edit/{id}', controller='group_formalchemy', action='edit') # These named routes are used for custom group forms which will use the # names below based on the group.type ('group' is the default type) with SubMapper(map, controller='group') as m: m.connect('group_index', '/group', action='index') m.connect('group_list', '/group/list', action='list') m.connect('group_new', '/group/new', action='new') m.connect('group_action', '/group/{action}/{id}', requirements=dict( action='|'.join(['edit', 'authz', 'delete', 'history']))) m.connect('group_read', '/group/{id}', action='read') register_package_plugins(map) register_group_plugins(map) # tags map.redirect('/tags', '/tag') map.redirect('/tags/{url:.*}', '/tag/{url}') map.redirect('/tag/read/{url:.*}', '/tag/{url}', _redirect_code='301 Moved Permanently') map.connect('/tag', controller='tag', action='index') map.connect('/tag/{id}', controller='tag', action='read') # users map.redirect('/users/{url:.*}', '/user/{url}') map.redirect('/user/', '/user') with SubMapper(map, controller='user') as m: m.connect('/user/edit', action='edit') # Note: openid users have slashes in their ids, so need the wildcard # in the route. m.connect('/user/dashboard', action='dashboard') m.connect('/user/followers/{id:.*}', action='followers') m.connect('/user/edit/{id:.*}', action='edit') m.connect('/user/reset/{id:.*}', action='perform_reset') m.connect('/user/register', action='register') m.connect('/user/login', action='login') m.connect('/user/_logout', action='logout') m.connect('/user/logged_in', action='logged_in') m.connect('/user/logged_out', action='logged_out') m.connect('/user/logged_out_redirect', action='logged_out_page') m.connect('/user/reset', action='request_reset') m.connect('/user/me', action='me') m.connect('/user/set_lang/{lang}', action='set_lang') m.connect('/user/{id:.*}', action='read') m.connect('/user', action='index') with SubMapper(map, controller='revision') as m: m.connect('/revision', action='index') m.connect('/revision/edit/{id}', action='edit') m.connect('/revision/diff/{id}', action='diff') m.connect('/revision/list', action='list') m.connect('/revision/{id}', action='read') # feeds with SubMapper(map, controller='feed') as m: m.connect('/feeds/group/{id}.atom', action='group') m.connect('/feeds/tag/{id}.atom', action='tag') m.connect('/feeds/dataset.atom', action='general') m.connect('/feeds/custom.atom', action='custom') map.connect('ckanadmin_index', '/ckan-admin', controller='admin', action='index') map.connect('ckanadmin', '/ckan-admin/{action}', controller='admin') # Storage routes with SubMapper( map, controller='ckan.controllers.storage:StorageAPIController') as m: m.connect('storage_api', '/api/storage', action='index') m.connect('storage_api_set_metadata', '/api/storage/metadata/{label:.*}', action='set_metadata', conditions=PUT_POST) m.connect('storage_api_get_metadata', '/api/storage/metadata/{label:.*}', action='get_metadata', conditions=GET) m.connect('storage_api_auth_request', '/api/storage/auth/request/{label:.*}', action='auth_request') m.connect('storage_api_auth_form', '/api/storage/auth/form/{label:.*}', action='auth_form') with SubMapper( map, controller='ckan.controllers.storage:StorageController') as m: m.connect('storage_upload', '/storage/upload', action='upload') m.connect('storage_upload_handle', '/storage/upload_handle', action='upload_handle') m.connect('storage_upload_success', '/storage/upload/success', action='success') m.connect('storage_upload_success_empty', '/storage/upload/success_empty', action='success_empty') m.connect('storage_file', '/storage/f/{label:.*}', action='file') with SubMapper(map, controller='util') as m: m.connect('/i18n/strings_{lang}.js', action='i18n_js_strings') m.connect('/util/redirect', action='redirect') m.connect('/testing/primer', action='primer') m.connect('/testing/markup', action='markup') for plugin in routing_plugins: map = plugin.after_map(map) # sometimes we get requests for favicon.ico we should redirect to # the real favicon location. map.redirect('/favicon.ico', config.get('ckan.favicon')) map.redirect('/*(url)/', '/{url}', _redirect_code='301 Moved Permanently') map.connect('/*url', controller='template', action='view') return map
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # CUSTOM ROUTES HERE map.connect('home', '/', controller='news', action='index', title='index') map.connect('home', '/index', controller='news', action='index', title='index') map.connect('article', '/news/{title}', controller='news', action='article') map.connect('newshome', '/News', controller='news', action='news') map.connect('photo', '/Photo-Gallery/{title}', controller='news', action='photo') map.connect('/{title}', controller='news', action='show') return map
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = False map.sub_domains = True map.sub_domains_ignore = ["www", None] has_subdomain = dict(sub_domain=True) no_subdomain = dict(sub_domain=False) # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # Web API # Wraps a safe subset of adroll.api for public consumption. map.connect('/api/v{version}/{module}/{function}/{id}', version=1, controller='api', action='dispatch') map.connect('/api/v{version}/{module}/{function}', version=1, controller='api', action='dispatch') map.connect('/api/v{version}/{module}', version=1, controller='api', action='dispatch') # Shortened webservice routes. Meant to be accessed from api.adroll.com per documentation. map.connect('/v1/{module}/{function}/{id}', version=1, controller='api', action='dispatch', sub_domain='api') map.connect('/v1/{module}/{function}', version=1, controller='api', action='dispatch', sub_domain='api') map.connect('/v1/{module}', version=1, controller='api', action='dispatch', sub_domain='api') # NO subdomain map.connect('/', controller='index', action='index', conditions=no_subdomain) map.connect('/login', controller='auth', action='login', conditions=no_subdomain) map.connect('/register', controller='auth', action='register', conditions=no_subdomain) map.connect('/create', controller='organization/create', action='index', conditions=no_subdomain) map.connect('/invite/{id}', controller='invite', action='index', conditions=no_subdomain) # in the application with subdomain map.connect('/', controller='organization/home', action='index', conditions=has_subdomain) map.connect('/pending', controller='organization/auth', action='pending', conditions=has_subdomain) map.connect('/login', controller='organization/auth', action='login', conditions=has_subdomain) map.connect('/register', controller='organization/auth', action='register', conditions=has_subdomain) #TODO, figure out way to not have to have two for trailing slash or not. map.connect('/project/{slug}', controller='organization/project', action='view', conditions=has_subdomain) map.connect('/project/{slug}/', controller='organization/project', action='view', conditions=has_subdomain) map.connect('/project/{slug}/{path:.*}', controller='organization/project', action='view', conditions=has_subdomain) map.connect('/file/delete/{id}', controller='organization/file', action='delete', conditions=has_subdomain) map.connect('/file/change/{change}', controller='organization/file', action='change', conditions=has_subdomain) map.connect('/file/{project}/{file}', controller='organization/file', action='view', conditions=has_subdomain) map.connect('/psettings/{slug}', controller='organization/project', action='settings_index', conditions=has_subdomain) map.connect('/psettings/{slug}/general', controller='organization/project', action='settings_general', conditions=has_subdomain) map.connect('/psettings/{slug}/users', controller='organization/project', action='settings_users', conditions=has_subdomain) map.connect('/projects', controller='organization/home', action='index', conditions=has_subdomain) map.connect('/projects/{action}', controller='organization/project', action='index', conditions=has_subdomain) map.connect('/projects/{action}/{slug}', controller='organization/project', action='index', conditions=has_subdomain) map.connect('/settings', controller='organization/settings', action='users', conditions=has_subdomain) map.connect('/settings/{action}', controller='organization/settings', action='users', conditions=has_subdomain) #dont care on subdomain map.connect('/admin', controller='admin/search', action='index') map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') return map
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # CUSTOM ROUTES HERE map.connect('/', controller='hello', action='index') map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') return map
from routes import Mapper map = Mapper() print map map.connect('name', '/blog/{id}', controller='main', action='index') result = map.match('/blog/1') print result
def make_map(global_conf={}, app_conf={}): map = Mapper() mc = map.connect admin_routes.add(mc) mc('/login', controller='front', action='login') mc('/logout', controller='front', action='logout') mc('/adminon', controller='front', action='adminon') mc('/adminoff', controller='front', action='adminoff') mc('/submit', controller='front', action='submit') mc('/imagebrowser', controller='front', action='imagebrowser') mc('/imagebrowser/:article', controller='front', action='imagebrowser') mc('/validuser', controller='front', action='validuser') mc('/over18', controller='post', action='over18') mc('/search/results', controller='front', action='search_results') mc('/about/:location', controller='front', action='editreddit', location='about') mc('/categories/create', controller='front', action='newreddit') mc('/categories/:where', controller='reddits', action='listing', where='popular', requirements=dict(where="popular|new|banned")) mc('/categories/mine/:where', controller='myreddits', action='listing', where='subscriber', requirements=dict(where='subscriber|contributor|moderator')) #mc('/stats', controller='front', action='stats') mc('/user/:username/:where', controller='user', action='listing', where='profile') mc('/prefs/:location', controller='front', action='prefs', location='options') mc('/related/:article/:title', controller='front', action='related', title=None) mc('/lw/:article/:title/:comment', controller='front', action='comments', title=None, comment=None) mc('/edit/:article', controller='front', action="editarticle") mc('/stylesheet', controller='front', action='stylesheet') mc('/', controller='promoted', action='listing') for name, page in allWikiPagesCached.items(): if page.has_key('route'): mc("/wiki/" + page['route'], controller='wikipage', action='wikipage', name=name) mc('/invalidate_cache', controller='wikipage', action='invalidate_cache') listing_controllers = "hot|saved|toplinks|topcomments|new|recommended|randomrising|comments|blessed|recentposts|edits|promoted" mc('/:controller', action='listing', requirements=dict(controller=listing_controllers)) # Can't use map.resource because the version of the Routing module we're # using doesn't support the controller_action kw arg #map.resource('meetup', 'meetups', collection_actions=['create', 'new']) mc('/meetups/create', action='create', controller='meetups') mc('/meetups', action='listing', controller='meetupslisting') mc('/meetups/new', action='new', controller='meetups') mc('/meetups/:id/edit', action='edit', controller='meetups') mc('/meetups/:id/update', action='update', controller='meetups') mc('/meetups/:id', action='show', controller='meetups') mc('/tag/:tag', controller='tag', action='listing', where='tag') mc('/by_id/:names', controller='byId', action='listing') mc('/:sort', controller='browse', sort='top', action='listing', requirements=dict(sort='top|controversial')) mc('/message/compose', controller='message', action='compose') mc('/message/:where', controller='message', action='listing') mc('/:action', controller='front', requirements=dict(action="password|random|framebuster")) mc('/:action', controller='embed', requirements=dict(action="help|blog")) mc('/:action', controller='toolbar', requirements=dict(action="goto|toolbar")) mc('/resetpassword/:key', controller='front', action='resetpassword') mc('/resetpassword', controller='front', action='resetpassword') mc('/post/:action', controller='post', requirements=dict(action="options|over18|optout|optin|login|reg")) mc('/api/:action', controller='api') mc('/captcha/:iden', controller='captcha', action='captchaimg') mc('/doquery', controller='query', action='doquery') mc('/code', controller='redirect', action='redirect', dest='http://code.google.com/p/lesswrong/') mc('/about-less-wrong', controller='front', action='about') mc('/issues', controller='front', action='issues') # Google webmaster tools verification page mc('/googlea26ba8329f727095.html', controller='front', action='blank') # This route handles displaying the error page and # graphics used in the 404/500 # error pages. It should likely stay at the top # to ensure that the error page is # displayed properly. mc('/error/document/:id', controller='error', action="document") mc("/*url", controller='front', action='catchall') return map
def make_map(config): """Create, configure and return the routes Mapper""" from pylons import config as c c.update(config) from lr.model import LRNode map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) def mapResource(config_key, member_name, collection_name): try: service_doc_id = config[config_key] service_doc = h.getServiceDocument(service_doc_id) if service_doc is not None and service_doc["active"]: map.resource(member_name, collection_name) if member_name == 'swordservice': map.connect("/swordpub", controller='swordservice', action='create') log.info( "Enabling service route for: {0} member: {1} collection: {2}" .format(service_doc_id, member_name, collection_name)) else: log.info( "Service route for {0} is disabled".format(service_doc_id)) except: log.exception( "Exception caught: Not enabling service route for config: {0} member: {1} collection: {2}" .format(config_key, member_name, collection_name)) map.resource('filter', 'filters', controller='contrib/filters', path_prefix='/contrib', name_prefix='contrib_') mapResource('lr.status.docid', 'status', 'status') mapResource('lr.distribute.docid', 'distribute', 'distribute') if not LRNode.nodeDescription.gateway_node: mapResource('lr.publish.docid', 'publish', 'publish') mapResource('lr.obtain.docid', 'obtain', 'obtain') mapResource('lr.description.docid', 'description', 'description') mapResource('lr.services.docid', 'services', 'services') mapResource('lr.policy.docid', 'policy', 'policy') mapResource('lr.harvest.docid', 'harvest', 'harvest') # Value added services mapResource('lr.oaipmh.docid', 'OAI-PMH', 'OAI-PMH') mapResource('lr.slice.docid', 'slice', 'slice') mapResource('lr.sword.docid', 'swordservice', 'swordservice') map.minimization = False map.explicit = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # CUSTOM ROUTES HERE map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') return map
def initialize(self, database): self.mapper = Mapper() self.mapper.connect(None, "/{action_type}/{queue}")
def make_map(): map = Mapper() mc = map.connect for plugin in reversed(config['r2.plugins']): plugin.add_routes(mc) mc('/admin/', controller='awards') mc('/robots.txt', controller='robots', action='robots') mc('/crossdomain', controller='robots', action='crossdomain') mc('/login', controller='forms', action='login') mc('/register', controller='forms', action='register') mc('/logout', controller='forms', action='logout') mc('/verify', controller='forms', action='verify') mc('/adminon', controller='forms', action='adminon') mc('/adminoff', controller='forms', action='adminoff') mc('/submit', controller='front', action='submit') mc('/over18', controller='post', action='over18') mc('/rules', controller='front', action='rules') mc('/sup', controller='front', action='sup') mc('/traffic', controller='front', action='site_traffic') mc('/traffic/languages/:langcode', controller='front', action='lang_traffic', langcode='') mc('/traffic/adverts/:code', controller='front', action='advert_traffic', code='') mc('/traffic/subreddits/report', controller='front', action='subreddit_traffic_report') mc('/account-activity', controller='front', action='account_activity') mc('/subreddits/create', controller='front', action='newreddit') mc('/subreddits/search', controller='front', action='search_reddits') mc('/subreddits/login', controller='forms', action='login') mc('/subreddits/:where', controller='reddits', action='listing', where='popular', requirements=dict(where="popular|new|banned|employee|gold")) # If no subreddit is specified, might as well show a list of 'em. mc('/r', controller='redirect', action='redirect', dest='/subreddits') mc('/subreddits/mine/:where', controller='myreddits', action='listing', where='subscriber', requirements=dict(where='subscriber|contributor|moderator')) # These routes are kept for backwards-compatibility reasons # Using the above /subreddits/ ones instead is preferable mc('/reddits/create', controller='front', action='newreddit') mc('/reddits/search', controller='front', action='search_reddits') mc('/reddits/login', controller='forms', action='login') mc('/reddits/:where', controller='reddits', action='listing', where='popular', requirements=dict(where="popular|new|banned")) mc('/reddits/mine/:where', controller='myreddits', action='listing', where='subscriber', requirements=dict(where='subscriber|contributor|moderator')) mc('/buttons', controller='buttons', action='button_demo_page') #/button.js and buttonlite.js - the embeds mc('/button', controller='buttons', action='button_embed') mc('/buttonlite', controller='buttons', action='button_lite') mc('/widget', controller='buttons', action='widget_demo_page') mc('/bookmarklets', controller='buttons', action='bookmarklets') mc('/awards', controller='front', action='awards') mc('/awards/confirm/:code', controller='front', action='confirm_award_claim') mc('/awards/claim/:code', controller='front', action='claim_award') mc('/awards/received', controller='front', action='received_award') mc('/i18n', controller='redirect', action='redirect', dest='http://www.reddit.com/r/i18n') mc('/feedback', controller='redirect', action='redirect', dest='/contact') mc('/contact', controller='front', action='contact_us') mc('/jobs', controller='redirect', action='redirect', dest='https://jobs.lever.co/reddit') mc('/admin/awards', controller='awards') mc('/admin/awards/:awardcn/:action', controller='awards', requirements=dict(action="give|winners")) mc('/admin/creddits', controller='admintool', action='creddits') mc('/admin/gold', controller='admintool', action='gold') mc('/admin/errors', controller='errorlog') # Username-relative userpage redirects mc('/user/me', controller='user', action='rel_user_redirect') mc('/user/me/*rest', controller='user', action='rel_user_redirect') mc('/user/:username/about', controller='user', action='about', where='overview') mc('/user/:username/:where', controller='user', action='listing', where='overview') mc('/user/:username/saved/:category', controller='user', action='listing', where='saved') multi_prefixes = ( partial_connect(mc, path_prefix='/user/:username/m/:multipath'), partial_connect(mc, path_prefix='/me/m/:multipath', my_multi=True), partial_connect(mc, path_prefix='/me/f/:filtername'), ) for connect in multi_prefixes: connect('/', controller='hot', action='listing') connect('/submit', controller='front', action='submit') connect('/:sort', controller='browse', sort='top', action='listing', requirements=dict(sort='top|controversial')) connect( '/:controller', action='listing', requirements=dict(controller="hot|new|rising|randomrising|ads")) mc('/user/:username/:where/:show', controller='user', action='listing') mc('/explore', controller='front', action='explore') mc('/api/recommend/feedback', controller='api', action='rec_feedback') mc('/about/sidebar', controller='front', action='sidebar') mc('/about/sticky', controller='front', action='sticky') mc('/about/flair', controller='front', action='flairlisting') mc('/about', controller='front', action='about') for connect in (mc, ) + multi_prefixes: connect('/about/message/:where', controller='message', action='listing') connect('/about/log', controller='front', action='moderationlog') connect('/about/:location', controller='front', action='spamlisting', requirements=dict( location='reports|spam|modqueue|unmoderated|edited')) connect( '/about/:where', controller='userlistlisting', requirements=dict( where= 'contributors|banned|wikibanned|wikicontributors|moderators'), action='listing') connect('/about/:location', controller='front', action='editreddit', requirements=dict(location='edit|stylesheet|traffic|about')) connect('/comments', controller='comments', action='listing') connect('/comments/gilded', action='listing', controller='gilded') connect('/gilded', action='listing', controller='gilded') connect('/search', controller='front', action='search') mc('/u/:username', controller='redirect', action='user_redirect') mc('/u/:username/*rest', controller='redirect', action='user_redirect') # preserve timereddit URLs from 4/1/2012 mc('/t/:timereddit', controller='redirect', action='timereddit_redirect') mc('/t/:timereddit/*rest', controller='redirect', action='timereddit_redirect') # /prefs/friends is also aliased to /api/v1/me/friends mc('/prefs/:where', controller='userlistlisting', action='user_prefs', requirements=dict(where='blocked|friends')) mc('/prefs/:location', controller='forms', action='prefs', location='options') mc('/info/0:article/*rest', controller='front', action='oldinfo', dest='comments', type='ancient') mc('/info/:article/:dest/:comment', controller='front', action='oldinfo', type='old', dest='comments', comment=None) mc('/related/:article/:title', controller='front', action='related', title=None) mc('/details/:article/:title', controller='front', action='details', title=None) mc('/traffic/:link/:campaign', controller='front', action='traffic', campaign=None) mc('/comments/:article/:title/:comment', controller='front', action='comments', title=None, comment=None) mc('/duplicates/:article/:title', controller='front', action='duplicates', title=None) mc('/mail/optout', controller='forms', action='optout') mc('/mail/optin', controller='forms', action='optin') mc('/stylesheet', controller='front', action='stylesheet') mc('/frame', controller='front', action='frame') mc('/framebuster/:blah', controller='front', action='framebuster') mc('/framebuster/:what/:blah', controller='front', action='framebuster') # sponsor endpoints mc('/sponsor/report', controller='sponsor', action='report') mc('/sponsor/inventory', controller='sponsor', action='promote_inventory') mc('/sponsor/roadblock', controller='sponsor', action="roadblock") mc('/sponsor/lookup_user', controller='sponsor', action="lookup_user") # sponsor listings mc('/sponsor/promoted/:sort', controller='sponsorlisting', action='listing', requirements=dict(sort="future_promos|pending_promos|unpaid_promos|" "rejected_promos|live_promos|underdelivered|" "reported|house|fraud|all")) mc('/sponsor', controller='sponsorlisting', action="listing", sort="all") mc('/sponsor/promoted/', controller='sponsorlisting', action="listing", sort="all") mc('/sponsor/promoted/live_promos/:sr', controller='sponsorlisting', sort='live_promos', action='listing') # listings of user's promos mc('/promoted/:sort', controller='promotelisting', action="listing", requirements=dict(sort="future_promos|pending_promos|unpaid_promos|" "rejected_promos|live_promos|all")) mc('/promoted/', controller='promotelisting', action="listing", sort="all") # editing endpoints mc('/promoted/new_promo', controller='promote', action='new_promo') mc('/promoted/edit_promo/:link', controller='promote', action='edit_promo') mc('/promoted/pay/:link/:campaign', controller='promote', action='pay') mc('/promoted/refund/:link/:campaign', controller='promote', action='refund') mc('/health', controller='health', action='health') mc('/health/ads', controller='health', action='promohealth') mc('/health/caches', controller='health', action='cachehealth') mc('/', controller='hot', action='listing') mc('/:controller', action='listing', requirements=dict(controller="hot|new|rising|randomrising|ads")) mc('/saved', controller='user', action='saved_redirect') mc('/by_id/:names', controller='byId', action='listing') mc('/:sort', controller='browse', sort='top', action='listing', requirements=dict(sort='top|controversial')) mc('/message/compose', controller='message', action='compose') mc('/message/messages/:mid', controller='message', action='listing', where="messages") mc('/message/:where', controller='message', action='listing') mc('/message/moderator/:subwhere', controller='message', action='listing', where='moderator') mc('/thanks', controller='forms', action="claim", secret='') mc('/thanks/:secret', controller='forms', action="claim") mc('/gold', controller='forms', action="gold", is_payment=False) mc('/gold/payment', controller='forms', action="gold", is_payment=True) mc('/gold/creditgild/:passthrough', controller='forms', action='creditgild') mc('/gold/thanks', controller='front', action='goldthanks') mc('/gold/subscription', controller='forms', action='subscription') mc('/gilding', controller='front', action='gilding') mc('/creddits', controller='redirect', action='redirect', dest='/gold?goldtype=creddits') mc('/password', controller='forms', action="password") mc('/:action', controller='front', requirements=dict(action="random|framebuster")) mc('/:action', controller='embed', requirements=dict(action="blog")) mc('/help/gold', controller='redirect', action='redirect', dest='/gold/about') mc('/help/:page', controller='policies', action='policy_page', conditions={'function': not_in_sr}, requirements={'page': 'privacypolicy|useragreement'}) mc('/wiki/create/*page', controller='wiki', action='wiki_create') mc('/wiki/edit/*page', controller='wiki', action='wiki_revise') mc('/wiki/revisions', controller='wiki', action='wiki_recent') mc('/wiki/revisions/*page', controller='wiki', action='wiki_revisions') mc('/wiki/settings/*page', controller='wiki', action='wiki_settings') mc('/wiki/discussions/*page', controller='wiki', action='wiki_discussions') mc('/wiki/pages', controller='wiki', action='wiki_listing') mc('/api/wiki/edit', controller='wikiapi', action='wiki_edit') mc('/api/wiki/hide', controller='wikiapi', action='wiki_revision_hide') mc('/api/wiki/delete', controller='wikiapi', action='wiki_revision_delete') mc('/api/wiki/revert', controller='wikiapi', action='wiki_revision_revert') mc('/api/wiki/alloweditor/:act', controller='wikiapi', requirements=dict(act="del|add"), action='wiki_allow_editor') mc('/wiki/*page', controller='wiki', action='wiki_page') mc('/wiki/', controller='wiki', action='wiki_page') mc('/:action', controller='wiki', requirements=dict(action="help|faq")) mc('/help/*page', controller='wiki', action='wiki_redirect') mc('/w/*page', controller='wiki', action='wiki_redirect') mc('/goto', controller='toolbar', action='goto') mc('/tb/:id', controller='toolbar', action='tb') mc('/toolbar/:action', controller='toolbar', requirements=dict(action="toolbar|inner|login")) mc('/toolbar/comments/:id', controller='toolbar', action='comments') mc('/c/:comment_id', controller='front', action='comment_by_id') mc('/s/*urloid', controller='toolbar', action='s') # additional toolbar-related rules just above the catchall mc('/resetpassword/:key', controller='forms', action='resetpassword') mc('/verification/:key', controller='forms', action='verify_email') mc('/resetpassword', controller='forms', action='resetpassword') mc('/modify_hsts_grant', controller='front', action='modify_hsts_grant') mc('/post/:action/:url_user', controller='post', requirements=dict(action="login|reg")) mc('/post/:action', controller='post', requirements=dict(action="options|over18|unlogged_options|optout" "|optin|login|reg|explore_settings")) mc('/api', controller='redirect', action='redirect', dest='/dev/api') mc('/api/distinguish/:how', controller='api', action="distinguish") mc('/api/spendcreddits', controller='ipn', action="spendcreddits") mc('/api/stripecharge/gold', controller='stripe', action='goldcharge') mc('/api/modify_subscription', controller='stripe', action='modify_subscription') mc('/api/cancel_subscription', controller='stripe', action='cancel_subscription') mc('/api/stripewebhook/gold/:secret', controller='stripe', action='goldwebhook') mc('/api/coinbasewebhook/gold/:secret', controller='coinbase', action='goldwebhook') mc('/api/rgwebhook/gold/:secret', controller='redditgifts', action='goldwebhook') mc('/api/ipn/:secret', controller='ipn', action='ipn') mc('/ipn/:secret', controller='ipn', action='ipn') mc('/api/:action/:url_user', controller='api', requirements=dict(action="login|register")) mc('/api/gadget/click/:ids', controller='api', action='gadget', type='click') mc('/api/gadget/:type', controller='api', action='gadget') mc('/api/:action', controller='promoteapi', requirements=dict(action=("promote|unpromote|edit_promo|link_thumb|" "freebie|promote_note|update_pay|" "edit_campaign|delete_campaign|" "add_roadblock|rm_roadblock|check_inventory|" "refund_campaign|terminate_campaign|" "review_fraud|create_promo"))) mc('/api/:action', controller='apiminimal', requirements=dict(action="new_captcha")) mc('/api/:type', controller='api', requirements=dict(type='wikibannednote|bannednote'), action='relnote') # Route /api/multi here to prioritize it over the /api/:action rule mc("/api/multi", controller="multiapi", action="multi", conditions={"method": ["POST"]}) mc('/api/:action', controller='api') mc('/api/recommend/sr/:srnames', controller='api', action='subreddit_recommendations') mc('/api/server_seconds_visibility', controller='api', action='server_seconds_visibility') mc("/api/multi/mine", controller="multiapi", action="my_multis") mc("/api/multi/user/:username", controller="multiapi", action="list_multis") mc("/api/multi/copy", controller="multiapi", action="multi_copy") mc("/api/multi/rename", controller="multiapi", action="multi_rename") mc("/api/multi/*multipath/r/:srname", controller="multiapi", action="multi_subreddit") mc("/api/multi/*multipath/description", controller="multiapi", action="multi_description") mc("/api/multi/*multipath", controller="multiapi", action="multi") mc("/api/filter/*multipath/r/:srname", controller="multiapi", action="multi_subreddit") mc("/api/filter/*multipath", controller="multiapi", action="multi") mc("/api/v1/:action", controller="oauth2frontend", requirements=dict(action="authorize")) mc("/api/v1/:action", controller="oauth2access", requirements=dict(action="access_token|revoke_token")) mc("/api/v1/user/:username/trophies", controller="apiv1user", action="usertrophies") mc("/api/v1/:action", controller="apiv1user") # Same controller/action as /prefs/friends mc("/api/v1/me/:where", controller="userlistlisting", action="user_prefs", requirements=dict(where="friends")) mc("/api/v1/me/:action", controller="apiv1user") mc("/api/v1/me/:action/:username", controller="apiv1user") mc("/api/v1/gold/gild/:fullname", controller="apiv1gold", action="gild") mc("/api/v1/gold/give/:username", controller="apiv1gold", action="give") mc('/dev', controller='redirect', action='redirect', dest='/dev/api') mc('/dev/api', controller='apidocs', action='docs') mc('/dev/api/:mode', controller='apidocs', action='docs', requirements=dict(mode="oauth")) mc("/button_info", controller="api", action="url_info", limit=1) mc('/captcha/:iden', controller='captcha', action='captchaimg') mc('/mediaembed/:link/:credentials', controller="mediaembed", action="mediaembed", credentials=None) mc('/code', controller='redirect', action='redirect', dest='http://github.com/reddit/') mc('/socialite', controller='redirect', action='redirect', dest='https://addons.mozilla.org/firefox/addon/socialite/') mc('/mobile', controller='redirect', action='redirect', dest='http://m.reddit.com/') mc('/authorize_embed', controller='front', action='authorize_embed') # Used for showing ads mc("/ads/", controller="ad", action="ad") mc("/try", controller="forms", action="try_compact") mc("/web/timings", controller="weblog", action="timings") mc("/web/log/:level", controller="weblog", action="message", requirements=dict(level="error")) # This route handles displaying the error page and # graphics used in the 404/500 # error pages. It should likely stay at the top # to ensure that the error page is # displayed properly. mc('/error/document/:id', controller='error', action="document") # these should be near the buttom, because they should only kick # in if everything else fails. It's the attempted catch-all # reddit.com/http://... and reddit.com/34fr, but these redirect to # the less-guessy versions at /s/ and /tb/ mc('/:linkoid', controller='toolbar', action='linkoid', requirements=dict(linkoid='[0-9a-z]{1,6}')) mc('/:urloid', controller='toolbar', action='s', requirements=dict(urloid=r'(\w+\.\w{2,}|https?).*')) mc("/*url", controller='front', action='catchall') return map
def initialize(self, database): self.mapper = Mapper() self.mapper.connect(None, "/{action}/{exchange}/{queue}") self.mapper.connect(None, "/{action}/{exchange}/") print 'fdd'
def make_map(global_conf={}, app_conf={}): map = Mapper() mc = map.connect admin_routes.add(mc) mc('/login', controller='forms', action='login') mc('/register', controller='forms', action='register') mc('/logout', controller='forms', action='logout') mc('/verify', controller='forms', action='verify') mc('/adminon', controller='forms', action='adminon') mc('/adminoff', controller='forms', action='adminoff') mc('/submit', controller='front', action='submit') mc('/validuser', controller='forms', action='validuser') mc('/over18', controller='post', action='over18') mc('/search', controller='front', action='search') mc('/sup', controller='front', action='sup') mc('/traffic', controller='front', action='site_traffic') mc('/account-activity', controller='front', action='account_activity') mc('/about/message/:where', controller='message', action='listing') mc('/about/log', controller='front', action='moderationlog') mc('/about/:location', controller='front', action='editreddit', location='about') mc('/reddits/create', controller='front', action='newreddit') mc('/reddits/search', controller='front', action='search_reddits') mc('/reddits/login', controller='forms', action='login') mc('/reddits/:where', controller='reddits', action='listing', where='popular', requirements=dict(where="popular|new|banned")) mc('/reddits/mine/:where', controller='myreddits', action='listing', where='subscriber', requirements=dict(where='subscriber|contributor|moderator')) mc('/buttons', controller='buttons', action='button_demo_page') mc('/upgradebuttons', controller='buttons', action='upgrade_buttons') #the frame mc('/button_content', controller='buttons', action='button_content') #/button.js and buttonlite.js - the embeds mc('/button', controller='buttonjs', action='button_embed') mc('/buttonlite', controller='buttons', action='button_lite') mc('/widget', controller='buttons', action='widget_demo_page') mc('/bookmarklets', controller='buttons', action='bookmarklets') mc('/iphonebookmarklet', controller='buttons', action='iphonebookmarklets') mc('/awards', controller='front', action='awards') mc('/i18n', controller='redirect', action='redirect', dest='http://www.reddit.com/r/i18n') mc('/feedback', controller='feedback', action='feedback') mc('/ad_inq', controller='feedback', action='ad_inq') mc('/admin/usage', controller='usage') # Used for editing ads mc('/admin/ads', controller='ads') mc('/admin/ads/:adcn/:action', controller='ads', requirements=dict(action="assign|srs")) mc('/admin/awards', controller='awards') mc('/admin/awards/:awardcn/:action', controller='awards', requirements=dict(action="give|winners")) mc('/admin/errors', controller='errorlog') mc('/admin/:action', controller='admin') mc('/user/:username/about', controller='user', action='about', where='overview') mc('/user/:username/:where', controller='user', action='listing', where='overview') mc('/prefs/:location', controller='forms', action='prefs', location='options') mc('/depmod', controller='forms', action='depmod') mc('/info/0:article/*rest', controller='front', action='oldinfo', dest='comments', type='ancient') mc('/info/:article/:dest/:comment', controller='front', action='oldinfo', type='old', dest='comments', comment=None) mc('/related/:article/:title', controller='front', action='related', title=None) mc('/details/:article/:title', controller='front', action='details', title=None) mc('/traffic/:article/:title', controller='front', action='traffic', title=None) mc('/comments/:article/:title/:comment', controller='front', action='comments', title=None, comment=None) mc('/duplicates/:article/:title', controller='front', action='duplicates', title=None) mc('/mail/optout', controller='forms', action='optout') mc('/mail/optin', controller='forms', action='optin') mc('/stylesheet', controller='front', action='stylesheet') mc('/frame', controller='front', action='frame') mc('/framebuster/:blah', controller='front', action='framebuster') mc('/framebuster/:what/:blah', controller='front', action='framebuster') mc('/promoted/edit_promo/:link', controller='promote', action='edit_promo') mc('/promoted/pay/:link/:indx', controller='promote', action='pay') mc('/promoted/graph', controller='promote', action='graph') mc('/promoted/:action', controller='promote', requirements=dict(action="edit_promo|new_promo|roadblock")) mc('/promoted/:sort', controller='promote', action="listing") mc('/promoted/', controller='promoted', action="listing", sort="") mc('/health', controller='health', action='health') mc('/', controller='hot', action='listing') listing_controllers = "hot|saved|new|randomrising|comments" mc('/:controller', action='listing', requirements=dict(controller=listing_controllers)) mc('/by_id/:names', controller='byId', action='listing') mc('/:sort', controller='browse', sort='top', action='listing', requirements=dict(sort='top|controversial')) mc('/message/compose', controller='message', action='compose') mc('/message/messages/:mid', controller='message', action='listing', where="messages") mc('/message/:where', controller='message', action='listing') mc('/message/moderator/:subwhere', controller='message', action='listing', where='moderator') mc('/thanks', controller='forms', action="thanks", secret='') mc('/thanks/:secret', controller='forms', action="thanks") mc('/gold', controller='forms', action="gold") mc('/password', controller='forms', action="password") mc('/:action', controller='front', requirements=dict(action="random|framebuster|selfserviceoatmeal")) mc('/:action', controller='embed', requirements=dict(action="help|blog|faq")) mc('/help/*anything', controller='embed', action='help') mc('/goto', controller='toolbar', action='goto') mc('/tb/:id', controller='toolbar', action='tb') mc('/toolbar/:action', controller='toolbar', requirements=dict(action="toolbar|inner|login")) mc('/toolbar/comments/:id', controller='toolbar', action='comments') mc('/c/:comment_id', controller='front', action='comment_by_id') mc('/s/*rest', controller='toolbar', action='s') # additional toolbar-related rules just above the catchall mc('/d/:what', controller='api', action='bookmarklet') mc('/resetpassword/:key', controller='forms', action='resetpassword') mc('/verification/:key', controller='forms', action='verify_email') mc('/resetpassword', controller='forms', action='resetpassword') mc('/post/:action/:url_user', controller='post', requirements=dict(action="login|reg")) mc('/post/:action', controller='post', requirements=dict( action="options|over18|unlogged_options|optout|optin|login|reg")) mc('/api/distinguish/:how', controller='api', action="distinguish") # wherever this is, google has to agree. mc('/api/gcheckout', controller='ipn', action='gcheckout') mc('/api/spendcreddits', controller='ipn', action="spendcreddits") mc('/api/ipn/:secret', controller='ipn', action='ipn') mc('/ipn/:secret', controller='ipn', action='ipn') mc('/api/:action/:url_user', controller='api', requirements=dict(action="login|register")) mc('/api/gadget/click/:ids', controller='api', action='gadget', type='click') mc('/api/gadget/:type', controller='api', action='gadget') mc('/api/:action', controller='promote', requirements=dict( action= "promote|unpromote|edit_promo|link_thumb|freebie|promote_note|update_pay|refund|traffic_viewer|rm_traffic_viewer|edit_campaign|delete_campaign|meta_promo|add_roadblock|rm_roadblock" )) mc('/api/:action', controller='apiminimal', requirements=dict(action="new_captcha")) mc('/api/:action', controller='api') mc("/api/v1/:action", controller="oauth2frontend", requirements=dict(action="authorize")) mc("/api/v1/:action", controller="oauth2access", requirements=dict(action="access_token")) mc("/api/v1/:action", controller="apiv1") mc("/button_info", controller="api", action="info", limit=1) mc('/captcha/:iden', controller='captcha', action='captchaimg') mc('/mediaembed/:link', controller="mediaembed", action="mediaembed") mc('/doquery', controller='query', action='doquery') mc('/store', controller='redirect', action='redirect', dest='http://store.reddit.com/index.html') mc('/code', controller='redirect', action='redirect', dest='http://github.com/reddit/') mc('/mobile', controller='redirect', action='redirect', dest='http://m.reddit.com/') mc('/authorize_embed', controller='front', action='authorize_embed') # Used for showing ads mc("/ads/", controller="ad", action="ad") mc("/ads/r/:reddit_name/:keyword", controller="ad", action="ad", keyword=None) mc("/ads/:codename", controller="ad", action="ad_by_codename") mc("/try", controller="forms", action="try_compact") mc('/comscore-iframe/', controller='mediaembed', action='comscore') mc('/comscore-iframe/*url', controller='mediaembed', action='comscore') # This route handles displaying the error page and # graphics used in the 404/500 # error pages. It should likely stay at the top # to ensure that the error page is # displayed properly. mc('/error/document/:id', controller='error', action="document") # these should be near the buttom, because they should only kick # in if everything else fails. It's the attempted catch-all # reddit.com/http://... and reddit.com/34fr, but these redirect to # the less-guessy versions at /s/ and /tb/ mc('/:linkoid', controller='toolbar', action='linkoid', requirements=dict(linkoid='[0-9a-z]{1,6}')) mc('/:urloid', controller='toolbar', action='urloid', requirements=dict(urloid=r'(\w+\.\w{2,}|https?).*')) mc("/*url", controller='front', action='catchall') return map
from routes import Mapper from cc.engine.licenses import routing as licenses_routing from cc.engine.chooser import routing as chooser_routing from cc.engine.characteristic import routing as characteristic_routing mapping = Mapper() mapping.minimization = False mapping.connect("index", "/", controller="cc.engine.views:root_view") mapping.connect('/publicdomain/', controller="cc.engine.licenses.views:publicdomain_view") mapping.extend(licenses_routing.licenses_routes, '/licenses') mapping.extend(licenses_routing.cc0_routes, '/publicdomain/zero') mapping.extend(licenses_routing.mark_routes, '/publicdomain/mark') mapping.extend(chooser_routing.chooser_routes, '/choose') mapping.extend(characteristic_routing.characteristic_routes, '/characteristic') mapping.connect('/license/work-html-popup', controller="cc.engine.views:work_html_redirect") mapping.connect('/license/{remaining_url:.*}', controller="cc.engine.views:license_redirect")
class WSGIApplication: def __init__(self, **config): self.config = config self.mapper = Mapper() self.registory = {} self._wsmanager = WebSocketManager() super().__init__() def _match(self, req): # Note: Invoke the new API, first. If the arguments unmatched, # invoke the old API. try: return self.mapper.match(environ=req.environ) except TypeError: self.mapper.environ = req.environ return self.mapper.match(req.path_info) @wsgify_hack def __call__(self, req, start_response): match = self._match(req) if not match: return webob.exc.HTTPNotFound() req.start_response = start_response req.urlvars = match link = URLGenerator(self.mapper, req.environ) data = None name = match['controller'].__name__ if name in self.registory: data = self.registory[name] controller = match['controller'](req, link, data, **self.config) controller.parent = self return controller(req) def register(self, controller, data=None): def _target_filter(attr): if not inspect.ismethod(attr) and not inspect.isfunction(attr): return False if not hasattr(attr, 'routing_info'): return False return True methods = inspect.getmembers(controller, _target_filter) for method_name, method in methods: routing_info = getattr(method, 'routing_info') name = routing_info['name'] path = routing_info['path'] conditions = {} if routing_info.get('methods'): conditions['method'] = routing_info['methods'] requirements = routing_info.get('requirements') or {} self.mapper.connect(name, path, controller=controller, requirements=requirements, action=method_name, conditions=conditions) if data: self.registory[controller.__name__] = data @property def websocketmanager(self): return self._wsmanager
import os import MySQLdb import jinja2 # Setup a mapper from routes import Mapper map = Mapper() #map.resource("user", "users") map.connect("add user", "/user", controller="addUser", action="add", conditions=dict(method=["GET"])) map.connect("post user", "/user", controller="postUser", action="post", conditions=dict(method=["POST"])) map.connect("update user", "/user/{id}", controller="updateUser", action="update", conditions=dict(method=["GET"])) map.connect("put user", "/user/{id}", controller="putUser",
def make_map( global_conf, app_conf, ): ''' Create, configure and return the routes Mapper There are the three main controllers: /admin /validate /system ''' routeMap = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) routeMap.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved routeMap.connect('/error/{action}', controller='error') routeMap.connect('/error/{action}/{id}', controller='error') # routeMap.connect('/{controller}/{action}') # routeMap.connect('/{controller}/{action}/{id}') # the first / - default will be taken!! # in case of selfservice, we route the default / to selfservice selfservice = app_conf.get('service.selfservice', 'True') == 'True' if selfservice: routeMap.connect('/selfservice/custom-style.css', controller='selfservice', action='custom_style') routeMap.connect('/selfservice', controller='selfservice', action='index') routeMap.connect('/', controller='selfservice', action='index') for cont in ['selfservice', 'account']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of support for a remote selfservice, we have to enable this hook userservice = app_conf.get('service.userservice', 'True') == 'True' if userservice: routeMap.connect('/userservice', controller='userservice', action='index') for cont in ['userservice']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of manage, we route the default / to manage manage = app_conf.get('service.manage', 'True') == 'True' if manage: routeMap.connect('/manage/custom-style.css', controller='manage', action='custom_style') routeMap.connect('/admin', controller='admin', action='show') routeMap.connect('/system', controller='system', action='getConfig') routeMap.connect('/manage/', controller='manage', action='index') routeMap.connect('/', controller='manage', action='index') for cont in ['admin', 'system', 'manage', 'audit', 'auth']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of validate, we route the default / to validate validate = app_conf.get('service.validate', 'True') == 'True' if validate: routeMap.connect('/validate', controller='validate', action='check') routeMap.connect('/', controller='validate', action='check') for cont in ['validate']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of validate, we route the default / to validate validate = app_conf.get('service.ocra', 'True') == 'True' if validate: routeMap.connect('/ocra', controller='ocra', action='checkstatus') for cont in ['ocra']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) openid = app_conf.get('service.openid', 'True') == 'True' if openid: # the default openid will be the status routeMap.connect('/openid/', controller='openid', action='status') for cont in ['openid']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # linotpGetotp.active getotp = global_conf.get('linotpGetotp.active', 'True') == 'True' if getotp: for cont in ['gettoken']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # linotp.selfTest self_test = global_conf.get('linotp.selfTest', 'True') == 'True' if self_test: for cont in ['testing']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) return routeMap
def __init__(self, **config): self.config = config self.mapper = Mapper() self.registory = {} super(WSGIApplication, self).__init__()
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) map.minimization = False map.explicit = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # CUSTOM ROUTES HERE map.connect("/areas/count", controller="areas", action="count") map.resource("area", "areas") map.connect("/lines/count", controller="lines", action="count") map.resource("line", "lines") map.connect("/points/count", controller="points", action="count") map.resource("point", "points") map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') return map
def make_map(config): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers']) map.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('/error/{action}', controller='error') map.connect('/error/{action}/{id}', controller='error') # CUSTOM ROUTES HERE map.connect('/', controller='root', action='index') map.connect('/index{.format}', controller='root', action='index') map.connect('/openid/{action}', controller='openidauth') map.connect('/twitter/{action}', controller='twitteroauth') map.connect('/oembed{.format}', controller='oembed', action='oembed', conditions=dict(method=['GET'])) map.connect('/user/all', controller='user', action='all', conditions=dict(method=['GET'])) map.connect('/user/{id}/badges{.format}', controller='user', action='edit_badges', conditions=dict(method=['GET'])) map.connect('/user/{id}/badges{.format}', controller='user', action='update_badges', conditions=dict(method=['POST'])) # Old dashboard map.connect('/user/{id}/dashboard', controller='user', action='legacy_dashboard') map.connect('/user/{id}/dashboard_proposals', controller='user', action='legacy_dashboard_proposals') map.connect('/user/{id}/dashboard_pages', controller='user', action='legacy_dashboard_pages') # New event stream dashboard map.connect('/user/dashboard', controller='user', action='dashboard') map.connect('/user/dashboard/contributions', controller='user', action='dashboard_contributions') map.connect('/user/dashboard/votes', controller='user', action='dashboard_votes') map.connect('/user/dashboard/delegations', controller='user', action='dashboard_delegations') map.connect('/user/dashboard/messages', controller='user', action='dashboard_messages') map.connect('/welcome/{id}/{token}', controller='user', action='welcome') # avatar map.connect('/user/{id}_{x}x{y}.png', controller='user', action='avatar') map.connect('/user/{id}_{y}.png', controller='user', action='avatar') map.resource('user', 'user', member={'votes': 'GET', 'delegations': 'GET', 'instances': 'GET', 'about': 'GET', 'latest_events': 'GET', 'latest_contributions': 'GET', 'latest_milestones': 'GET', 'latest_votes': 'GET', 'latest_delegations': 'GET', 'watchlist': 'GET', 'groupmod': 'GET', 'ban': 'GET', 'unban': 'GET', 'ask_delete': 'GET', 'revert': 'GET', 'reset': 'GET', 'activate': 'GET', 'ask_activate': 'GET', 'pending_activate': 'GET', 'resend': 'GET', 'set_password': '******', 'generate_welcome_link': 'POST'}, collection={'complete': 'GET', 'filter': 'GET', # provide user-independent URLs to user settings 'redirect_settings': 'GET', 'redirect_settings_login': '******', 'redirect_settings_notifications': 'GET', 'redirect_settings_advanced': 'GET', 'redirect_settings_optional': 'GET', }) # TODO work this into a complete subcontroller. map.connect('/user/{id}/message.{format}', controller='message', action='create', conditions=dict(method=['POST', 'PUT'])) map.connect('/user/{id}/message', controller='message', action='create', conditions=dict(method=['POST', 'PUT'])) map.connect('/user/{id}/message/new.{format}', controller='message', action='new', conditions=dict(method=['GET'])) map.connect('/user/{id}/message/new', controller='message', action='new', conditions=dict(method=['GET'])) map.connect('/user/{id}/settings{.format}', controller='user', action='settings_personal', conditions=dict(method=['GET'])) map.connect('/user/{id}/settings{.format}', controller='user', action='settings_personal_update', conditions=dict(method=['PUT'])) map.connect('/user/{id}/settings/login{.format}', controller='user', action='settings_login', conditions=dict(method=['GET'])) map.connect('/user/{id}/settings/login{.format}', controller='user', action='settings_login_update', conditions=dict(method=['PUT'])) map.connect('/user/{id}/settings/notifications{.format}', controller='user', action='settings_notifications', conditions=dict(method=['GET'])) map.connect('/user/{id}/settings/notifications{.format}', controller='user', action='settings_notifications_update', conditions=dict(method=['PUT'])) map.connect('/user/{id}/settings/advanced{.format}', controller='user', action='settings_advanced', conditions=dict(method=['GET'])) map.connect('/user/{id}/settings/advanced{.format}', controller='user', action='settings_advanced_update', conditions=dict(method=['PUT'])) map.connect('/user/{id}/settings/optional{.format}', controller='user', action='settings_optional', conditions=dict(method=['GET'])) map.connect('/user/{id}/settings/optional{.format}', controller='user', action='settings_optional_update', conditions=dict(method=['PUT'])) map.connect('/message/new', controller='massmessage', action='new') map.connect('/message/preview', controller='massmessage', action='preview') map.connect('/message/create', controller='massmessage', action='create') map.connect('/message/{id}', controller='message', action='show') map.connect('/register', controller='user', action='new') map.connect('/login', controller='user', action='login') map.connect('/logout', controller='user', action='logout') map.connect('/post_logout', controller='user', action='post_logout') map.connect('/post_login', controller='user', action='post_login') map.connect('/perform_login', controller='user', action='perform_login') map.connect('/reset', controller='user', action='reset_form', conditions=dict(method=['GET'])) map.connect('/reset', controller='user', action='reset_request', conditions=dict(method=['POST'])) # map.connect('/proposal/{id}/badges', controller='proposal', # action='badges', conditions=dict(method=['GET'])) # map.connect('/proposal/{id}/badges', controller='proposal', # action='update_badges', conditions=dict(method=['POST'])) map.resource('proposal', 'proposal', member={'delegations': 'GET', 'activity': 'GET', 'ask_delete': 'GET', 'ask_adopt': 'GET', 'adopt': 'POST', 'badges': 'GET', 'update_badges': 'POST', 'comments': 'GET', 'history': 'GET'}, collection={'filter': 'GET'}) map.connect('/proposal/{proposal_id}/{selection_id}/details{.format}', controller='selection', action='details') map.connect('/proposal/{proposal_id}/message/new{.format}', controller='massmessage', action='new_proposal', conditions=dict(method=['GET'])) map.connect('/proposal/{proposal_id}/message{.format}', controller='massmessage', action='create_proposal', conditions=dict(method=['POST'])) map.resource('implementation', 'implementation', controller='selection', member={'ask_delete': 'GET'}, collection={'include': 'GET', 'propose': 'GET'}, parent_resource=dict(member_name='proposal', collection_name='proposal')) map.connect('/page/{id}_{x}x{y}.png', controller='page', action='logo') map.connect('/page/{id}_{y}.png', controller='page', action='logo') map.connect('/page/diff', controller='page', action='diff', conditions=dict(method=['GET'])) map.connect('/page/{id}/amendment{.format}', controller='page', action='show', amendment=True, conditions=dict(method=['GET']), ) map.connect('/page/{page}/amendment{.format}', controller='proposal', action='create', amendment=True, conditions=dict(method=['POST']) ) map.connect('/page/{page}/amendment/new{.format}', controller='proposal', action='new', amendment=True, conditions=dict(method=['GET']), ) map.connect('/page/{id}/amendment/{variant}{.format}', controller='page', action='show', amendment=True, conditions=dict(method=['GET']), ) map.connect('/page/{page}/amendment/{id}{.format}', controller='proposal', action='update', conditions=dict(method=['PUT']) ) map.connect('/page/{page}/amendment/{id}{.format}', controller='proposal', action='delete', conditions=dict(method=['DELETE']) ) map.connect('/page/{page}/amendment/{id}/edit{.format}', controller='proposal', action='edit', conditions=dict(method=['GET']), ) map.connect('/page/{page}/amendment/{id}/ask_delete{.format}', controller='proposal', action='ask_delete', conditions=dict(method=['GET']), ) map.connect('/page/{id}/{variant}/history{.format}', controller='page', action='history', conditions=dict(method=['GET'])) map.connect('/page/{id}/history{.format}', controller='page', action='history', conditions=dict(method=['GET']), ) map.connect('/page/{id}/comments{.format}', controller='page', action='comments', conditions=dict(method=['GET']), ) map.connect('/page/{id}/{variant}/branch', controller='page', action='edit', branch=True, conditions=dict(method=['GET'])) map.connect('/page/{id}/{variant}/ask_purge', controller='page', action='ask_purge', conditions=dict(method=['GET'])) map.connect('/page/{id}/{variant}/purge', controller='page', action='purge', conditions=dict(method=['POST', 'DELETE'])) map.connect('/page/{id};{text}/ask_purge_history', controller='page', action='ask_purge_history', conditions=dict(method=['GET'])) map.connect('/page/{id};{text}/purge_history', controller='page', action='purge_history', conditions=dict(method=['POST', 'DELETE'])) map.connect('/page/{id}/{variant}/edit.{format}', controller='page', action='edit', conditions=dict(method=['GET'])) map.connect('/page/{id}/{variant}/edit', controller='page', action='edit', conditions=dict(method=['GET'])) map.connect('/page/{id}/edit.{format}', controller='page', action='edit', conditions=dict(method=['GET'])) map.connect('/page/{id}/branch', controller='page', action='edit', branch=True, conditions=dict(method=['GET'])) map.connect('/page/{id}/edit', controller='page', action='edit', conditions=dict(method=['GET'])) map.connect('/page/{id}/ask_delete{.format}', controller='page', action='ask_delete', conditions=dict(method=['GET'])) map.connect('/page/{id}/{variant};{text}.{format}', controller='page', action='show', conditions=dict(method=['GET'])) map.connect('/page/{id}/{variant};{text}/branch', controller='page', action='edit', branch=True, conditions=dict(method=['GET'])) map.connect('/page/{id}/{variant};{text}', controller='page', action='show', conditions=dict(method=['GET'])) map.connect('/page/{id}/{variant}.{format}', controller='page', action='show', conditions=dict(method=['GET'])) map.connect('/page/{id}/{variant}', controller='page', action='show', conditions=dict(method=['GET'])) map.connect('/page/{id};{text}.{format}', controller='page', action='show', conditions=dict(method=['GET'])) map.connect('/page/{id};{text}/branch', controller='page', action='edit', branch=True, conditions=dict(method=['GET'])) map.connect('/page/{id};{text}', controller='page', action='show', conditions=dict(method=['GET'])) map.resource('page', 'page', member={'ask_delete': 'GET'}) # map.connect('/adopted', controller='proposal', action='adopted') map.resource('comment', 'comment', member={'history': 'GET', 'revert': 'GET', 'purge_history': 'GET', 'ask_delete': 'GET'}) map.connect('/comment/form/edit/{id}', controller='comment', action='edit_form') map.connect('/comment/form/create/{topic}', controller='comment', action='create_form', variant=None) map.connect('/comment/form/reply/{id}', controller='comment', action='reply_form') map.resource('milestone', 'milestone', member={'ask_delete': 'GET'}) map.connect('/poll/{id}/rate{.format}', controller='poll', action='rate', conditions=dict(method=['GET', 'POST'])) map.connect('/poll/{id}/widget{.format}', controller='poll', action='widget', conditions=dict(method=['GET', 'POST'])) map.connect('/poll/{id}/vote{.format}', controller='poll', action='vote', conditions=dict(method=['GET', 'POST'])) map.resource('poll', 'poll', member={'votes': 'GET', 'ask_delete': 'GET', 'widget': 'GET'}) map.connect('/badge{.format}', controller='badge', action='index', conditions=dict(method=['GET'])) map.connect('/badge/{badge_type}{.format}', controller='badge', action='index_type', conditions=dict(method=['GET'])) map.connect('/badge/{badge_type}/add{.format}', controller='badge', action='add', conditions=dict(method=['GET'])) map.connect('/badge/{badge_type}/add{.format}', controller='badge', action='create', conditions=dict(method=['POST'])) map.connect('/badge/edit/{id}{.format}', controller='badge', action="edit", conditions=dict(method=['GET'])) map.connect('/badge/edit/{id}{.format}', controller='badge', action="update", conditions=dict(method=['POST'])) map.connect('/badge/delete/{id}{.format}', controller='badge', action="ask_delete", conditions=dict(method=['GET'])) map.connect('/badge/delete/{id}{.format}', controller='badge', action="delete", conditions=dict(method=['POST'])) # category image map.connect('/category/{id}_{x}x{y}.png', controller='category', action='image') map.connect('/category/{id}_{y}.png', controller='category', action='image') map.connect('/category{.format}', controller='category', action='index', conditions=dict(method=['GET'])) map.connect('/category/{id}{.format}', controller='category', action='show', conditions=dict(method=['GET'])) map.connect('/category/{id}/description{.format}', controller='category', action='description', conditions=dict(method=['GET'])) map.connect('/category/{id}/events{.format}', controller='category', action='events', conditions=dict(method=['GET'])) map.connect('/category/{id}/milestones{.format}', controller='category', action='milestones', conditions=dict(method=['GET'])) # not using REST since tags may contain dots, thus failing format # detection. map.connect('/tag', controller='tag', action='index', conditions=dict(method=['GET'])) map.connect('/tag', controller='tag', action='create', conditions=dict(method=['POST'])) map.connect('/tag/autocomplete', controller='tag', action='autocomplete') map.connect('/untag', controller='tag', action='untag') map.connect('/untag_all', controller='tag', action='untag_all') map.connect('/tag/{id}', controller='tag', action='show') map.resource('delegation', 'delegation') # map.resource('delegations', 'delegation') map.connect('/d/{id}', controller='root', action='dispatch_delegateable') map.connect('/sitemap.xml', controller='root', action='sitemap_xml') map.connect('/robots.txt', controller='root', action='robots_txt') map.connect('/feed.rss', controller='root', action='index', format='rss') map.connect('/tutorials', controller='root', action='tutorials') map.connect('/search/filter', controller='search', action='filter') map.connect('/search{.format}', controller='search', action='query') map.connect('/abuse/report', controller='abuse', action='report') map.connect('/abuse/new', controller='abuse', action='new') map.connect('/instance/{id}_{x}x{y}.png', controller='instance', action='icon') map.connect('/instance/{id}_{y}.png', controller='instance', action='icon') map.connect('/instance/{id}/settings{.format}', controller='instance', action='settings_legacy', conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/overview{.format}', controller='instance', action='settings_overview', conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/overview{.format}', controller='instance', action='settings_overview_update', conditions=dict(method=['PUT'])) map.connect('/instance/{id}/settings/general{.format}', controller='instance', action='settings_general', conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/general{.format}', controller='instance', action='settings_general_update', conditions=dict(method=['PUT'])) map.connect('/instance/{id}/settings/process{.format}', controller='instance', action='settings_process', conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/process{.format}', controller='instance', action='settings_process_update', conditions=dict(method=['PUT'])) map.connect('/instance/{id}/settings/members{.format}', controller='instance', action='settings_members', conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/members{.format}', controller='instance', action='settings_members_update', conditions=dict(method=['PUT'])) map.connect('/instance/{id}/settings/advanced{.format}', controller='instance', action='settings_advanced', conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/advanced{.format}', controller='instance', action='settings_advanced_update', conditions=dict(method=['PUT'])) map.connect('/instance/{id}/settings/{part}/{badge_type}/add{.format}', controller='instance', action='settings_badges_add', conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/{part}/{badge_type}/add{.format}', controller='instance', action='settings_badges_create', conditions=dict(method=['POST'])) map.connect('/instance/{id}/settings/{part}/edit/{badge_id}{.format}', controller='instance', action="settings_badges_edit", conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/{part}/edit/{badge_id}{.format}', controller='instance', action="settings_badges_update", conditions=dict(method=['POST'])) map.connect('/instance/{id}/settings/{part}/delete/{badge_id}{.format}', controller='instance', action="settings_badges_ask_delete", conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/{part}/delete/{badge_id}{.format}', controller='instance', action="settings_badges_delete", conditions=dict(method=['POST'])) map.connect('/instance/{id}/message/new{.format}', controller='massmessage', action='new', conditions=dict(method=['GET'])) map.connect('/instance/{id}/message{.format}', controller='massmessage', action='create', conditions=dict(method=['POST'])) map.connect('/instance/{id}/message/preview{.format}', controller='massmessage', action='preview', conditions=dict(method=['POST'])) map.connect('/instance/{id}/members_import{.format}', controller='instance', action='members_import', conditions=dict(method=['GET'])) map.connect('/instance/{id}/members_import{.format}', controller='instance', action='members_import_save', conditions=dict(method=['PUT', 'POST'])) map.connect('/instance/{id}/settings/presets{.format}', controller='instance', action='settings_presets', conditions=dict(method=['GET'])) map.connect('/instance/{id}/settings/presets{.format}', controller='instance', action='settings_presets_update', conditions=dict(method=['PUT', 'POST'])) map.connect('/instance/{id}/presets{.format}', controller='instance', action='presets', conditions=dict(method=['GET'])) map.connect('/instance/{id}/presets{.format}', controller='instance', action='presets_update', conditions=dict(method=['POST'])) map.resource('instance', 'instance', member={'join': 'GET', 'ask_join': 'GET', 'leave': 'POST', 'filter': 'GET', 'ask_leave': 'GET', 'ask_delete': 'GET', 'style': 'GET', 'badges': 'GET', 'update_badges': 'POST', 'activity': 'GET'}) map.connect('/stats/', controller='stats') map.connect('/admin', controller='admin', action="index") map.connect('/admin/users/import{.format}', controller='admin', action="user_import", conditions=dict(method=['POST'])) map.connect('/admin/users/import{.format}', controller='admin', action="user_import_form", conditions=dict(method=['GET'])) map.connect('/admin/export', controller='admin', action='export_dialog') map.connect('/admin/export/do', controller='admin', action='export_do') map.connect('/admin/import{.format}', controller='admin', action='import_dialog') map.connect('/admin/import/do', controller='admin', action='import_do') map.connect('/admin/treatment/', controller='treatment', action='index', conditions={'method': 'GET'},) map.connect('/admin/treatment/', controller='treatment', action='create', conditions={'method': 'POST'},) map.connect('/admin/treatment/{key}/assign', controller='treatment', action='assign', conditions={'method': 'POST'},) map.connect('/admin/treatment/{key}/assigned', controller='treatment', action='assigned') map.connect('/static{.format}', controller='static', action='index', conditions=dict(method=['GET', 'HEAD'])) map.connect('/static{.format}', controller='static', action='make_new', conditions=dict(method=['POST'])) map.connect('/static/new{.format}', controller='static', action='new') map.connect('/static/edit/{lang}/*key', controller='static', action='edit', conditions=dict(method=['GET', 'HEAD'])) map.connect('/static/edit/{lang}/*(key){.format}', controller='static', action='update', conditions=dict(method=['POST'])) map.connect('/static/*(key){.format}', controller='static', action='serve') map.connect('/outgoing_link/{url_enc}', controller='redirect', action='outgoing_link', conditions=dict(method=['GET', 'HEAD'])) map.connect('/event/all{.format}', controller='event', action='all') map.connect('/event/carousel{.format}', controller='event', action='carousel') map.connect('/{controller}/{action}') map.connect('/{controller}/{action}/{id}') return map
class WebMapper(object): """ Loads the AST, link routes and run the post- and pre-conditions """ def __init__(self, dsl): sys.path.insert(0, os.getcwd()) # why ? self.mapper = Mapper() self.globs = dsl.globs self.types = dsl.types self.context = dsl.context self._hooks = {} self.options = {} self.root = dsl.root self.root_path = dsl.root_path def add(self, name, args): if name in self._hooks: raise NameError('%r already defined.' % name) params = {} for arg in args: if arg.type == 'assign': left = arg.left right = arg.right if isinstance(left, basestring): # XXX meh params[left] = right else: name_ = left.value if isinstance(right, list): params[name_] = arg.right else: params[name_] = arg.right.value else: raise NotImplementedError(arg) use = params.get('use', 'redbarrel.util.dummy') if 'url' in params: url = params.get('url', '/') if self.root_path: if url != '/': url = self.root_path + url else: url = self.root_path try: function = resolve_runner(use, self.root, url) except ImportError: # let's try in the context # # XXX ugly, need isolation function = None for lib in self.context.libraries: for callable in lib.dir(): name_ = '%s.%s' % (lib.name, callable) if name_ == use: function = lib.namespace[callable] break if function is None: logger.info(" => Error on %r" % name) raise params['func'] = function conditions = {} oldname = name params['name'] = name if 'method' in params: conditions['method'] = [str(method) for method in params['method']] self.mapper.connect(None, url, action=name, conditions=conditions) self._hooks[name] = WebHook(params, self.types) logger.info(" => %r hooked for %r" % (oldname, url)) else: logger.info(" => %r incomplete, ignoring" % name) def set_options(self, options): for option in options: if option.type == 'assign': left = option.left right = option.right if isinstance(left, basestring): # XXX meh self.options[left] = right else: self.options[left.value] = right.value else: raise NotImplementedError(option) def __call__(self, request): # finding a match match = self.mapper.routematch(environ=request.environ) if match is None: return HTTPNotFound() match, __ = match hook = self._hooks.get(match['action']) if hook is None: raise HTTPNotFound('Unknown URL %r' % request.path_info) hook.preconditions(request, self.globs) function = hook['func'] # the GET mapping is filled on GET and DELETE requests if request.method in ('GET', 'DELETE'): params = dict(request.GET) else: params = {} request.match = match try: result = function(self.globs, request, **params) except BackendError: err = traceback.format_exc() logger.error(err) raise HTTPServiceUnavailable(retry_after=self.retry_after) if isinstance(result, basestring): response = getattr(request, 'response', None) if response is None: response = Response(result) elif isinstance(result, str): response.body = result else: # if it's not str it's unicode, which really shouldn't happen response.body = result.encode('utf-8') else: # result is already a Response response = result hook.postconditions(response, request, self.globs) return response
def make_map(global_conf, app_conf,): """ Create, configure and return the routes Mapper There are the three main controllers: /admin /validate /system """ routeMap = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) routeMap.minimization = False # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved routeMap.connect('/error/{action}', controller='error') routeMap.connect('/error/{action}/{id}', controller='error') # check if we are in migration mode - # ! this will disable all other controllers ! migrate = app_conf.get('service.migrate', 'False') == 'True' if migrate: for cont in ['migrate']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) return routeMap # the first / - default will be taken!! # in case of selfservice, we route the default / to selfservice selfservice = app_conf.get('service.selfservice', 'True') == 'True' if selfservice: routeMap.connect( '/selfservice/custom-style.css', controller='selfservice', action='custom_style') routeMap.connect('/selfservice', controller='selfservice', action='index') routeMap.connect('/', controller='selfservice', action='index') for cont in ['selfservice', 'account']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of support for a remote selfservice, we have to enable this hook userservice = app_conf.get('service.userservice', 'True') == 'True' if userservice: routeMap.connect('/userservice', controller='userservice', action='index') for cont in ['userservice']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of support for monitoring, we have to enable this hook monitoring = app_conf.get('service.monitoring', 'True') == 'True' if monitoring: routeMap.connect('/monitoring', controller='monitoring', action='config') for cont in ['monitoring']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of support for reporting, we have to enable this hook reporting = app_conf.get('service.reporting', 'True') == 'True' if reporting: routeMap.connect('/reporting', controller='reporting') for cont in ['reporting']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of manage, we route the default / to manage manage = app_conf.get('service.manage', 'True') == 'True' if manage: routeMap.connect('/manage/custom-style.css', controller='manage', action='custom_style') routeMap.connect('/admin', controller='admin', action='show') routeMap.connect('/system', controller='system', action='getConfig') routeMap.connect('/manage/', controller='manage', action='index') routeMap.connect('/', controller='manage', action='index') for cont in ['admin', 'system', 'manage', 'audit', 'auth']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of validate, we route the default / to validate validate = app_conf.get('service.validate', 'True') == 'True' if validate: routeMap.connect('/validate', controller='validate', action='check') routeMap.connect('/', controller='validate', action='check') for cont in ['validate']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # ocra ocra = app_conf.get('service.ocra', 'True') == 'True' if ocra: routeMap.connect('/ocra', controller='ocra', action='checkstatus') for cont in ['ocra']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) openid = app_conf.get('service.openid', 'True') == 'True' if openid: # the default openid will be the status routeMap.connect('/openid/', controller='openid', action='status') for cont in ['openid']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # controller to get otp values # fallback for the getotp is the global linotpGetopt, but as all services # are in the app section, the app section one should be prefered getotp = (app_conf.get('service.getotp', global_conf.get('linotpGetotp.active', 'False')) == 'True') if getotp: for cont in ['gettoken']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # in case of u2f, we allow routes of type /u2f/realm/action u2f = app_conf.get('service.u2f', 'True') == 'True' if u2f: for cont in ['u2f']: routeMap.connect('/%s/{realm}/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}' % cont, controller=cont) # testing - for test setup: http sms provider callback self_test = app_conf.get('service.testing', 'False') == 'True' if self_test: for cont in ['testing']: routeMap.connect('/%s/{action}' % cont, controller=cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # linotp tools tools = global_conf.get('linotp.tools', 'True') == 'True' if tools: for cont in ['tools']: routeMap.connect('/%s/{action}' % cont, controller = cont) routeMap.connect('/%s/{action}/{id}' % cont, controller=cont) # check if the maintenance controller is activated maintenance = app_conf.get('service.maintenance', 'False') == 'True' if maintenance: routeMap.connect('/maintenance/{action}', controller='maintenance') return routeMap