我有一个典型的WSGI应用程序,如下所示:
app = webapp2.WSGIApplication([
('/site/path/one', 'package.module.ClassOne'),
('/site/path/two', 'package.module.ClassTwo'),
('/site/path/three', 'package.module.ClassThree'),
])
我希望以后能够在我的应用程序中检索路由列表,例如,在ClassOne中:
class ClassOne(webapp2.RequestHandler):
def get(self):
print ''' list of routes (e.g. '/site/path/one', '/site/path/two', etc.) '''
答案 0 :(得分:4)
看起来WSGIApplication有一个router属性
def __repr__(self):
routes = self.match_routes + [v for k, v in \
self.build_routes.iteritems() if v not in self.match_routes]
return '<Router(%r)>' % routes
您的wsgiApplication实例是webapp2.RequestHandler
所以我认为request.app.router
所以希望有一种更直接的方式,但如果不是,上面应该有问题吗?
提供了非常好的可搜索源代码答案 1 :(得分:2)
我刚写了这个函数来提取有关webapp2 app路由器中所有URI路由的有用信息,甚至包括使用webapp2_extras.routes.PathPrefixRoute创建的嵌套路由:
def get_route_list(router):
"""
Get a nested list of all the routes in the app's router
"""
def get_routes(r):
"""get list of routes from either a router object or a PathPrefixRoute object,
because they were too stupid to give them the same interface.
"""
if hasattr(r, 'match_routes'):
return r.match_routes
else:
return list(r.get_routes())
def get_doc(handler, method):
"""get the doc from the method if there is one,
otherwise get the doc from the handler class."""
if method:
return getattr(handler,method).__doc__
else:
return handler.__doc__
routes=[]
for i in get_routes(router):
if hasattr(i, 'handler'):
# I think this means it's a route, not a path prefix
cur_template = i.template
cur_handler = i.handler
cur_method = i.handler_method
cur_doc = get_doc(cur_handler,cur_method)
r={'template':cur_template, 'handler':cur_handler, 'method':cur_method, 'doc':cur_doc}
else:
r=get_route_list(i)
routes.append(r)
return routes
这将返回一个嵌套的列表列表,但是如果你只想要一个平面列表(就像我实际做的那样),你可以使用这里的函数展平它:Flattening a shallow list in python 注意:您可能需要编辑扁平化浅列表函数以避免迭代字典。也就是说,在这里添加:&#34; ...而不是isinstance(el,basestring)而不是isinstance(el,dict)&#34;
通过查看代码,这应该是显而易见的,但是我写这个的方式,对于每个路由,如果有自定义方法,它会为您提供自定义方法的文档字符串;否则,它会为您提供处理程序类的doc字符串。我们的想法是,这对于OP的目的应该是有用的,这也是我想要做的。