この関数を作成して、webapp2_extras.routes.PathPrefixRouteを使用して作成されたネストされたルートも含め、webapp2アプリルーター内のすべてのURIルートに関する有用な情報を抽出しました。
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
これはリストのネストされたリストを返しますが、フラットリストが必要な場合は(実際に行うように)、次の関数を使用してフラット化できます: pythonでの浅いリストのフラット化注
:おそらく、浅いリスト関数のフラット化を編集する必要がありますまた、辞書の繰り返しを避けるため。つまり、ここに追加します:「...そしてisinstance(el、basestring)ではなくisinstance(el、dict)ではない」
これはコードを見れば明らかですが、私がこれを書いた方法では、ルートごとに、カスタムメソッドがある場合はカスタムメソッドからのドキュメント文字列が提供されます。それ以外の場合は、ハンドラークラスのドキュメント文字列を提供します。これはOPの目的に役立つはずであり、それは私がやりたかったことでもあります。