3

私は次のような典型的な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.) '''
4

2 に答える 2

4

WSGIApplicationにルータープロパティがあるようです

ルーターには

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

それで、うまくいけば、もっと簡単な方法がありますが、そうでない場合は、上記がうまくいくはずですか?

Webapp2には、http: //webapp2.readthedocs.io/en/latest/で入手できる非常に優れた検索可能なソースコードがありました。

于 2012-10-25T23:48:01.497 に答える
2

この関数を作成して、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の目的に役立つはずであり、それは私がやりたかったことでもあります。

于 2014-07-12T18:57:34.807 に答える