0

有没有人想出一种在 Google App Engine 中进行自动路由的优雅方法?我最终得到了很长的路线列表,即

urls = routes.HandlerPrefixRoute(h+'index_handler.',[RedirectRoute(r'/',handler='IndexHandler')]),...

我想要这样 example.com/blog 会自动路由到 blog 处理程序,example.com/blog/method 会自动路由到 blog.method 方法。

4

1 回答 1

0

我已经找到了一个非常基本的使用 webapp2 和应用引擎进行路由的解决方案。我不打算在这里发布整个解决方案,但如果有人想看到它,请告诉我,我会将其发布在 github 上并向您发送链接。

我基本上只是使用 os 在我的处理程序目录中获取我的文件并遍历文件:

for file in os.listdir(directory):
    if file.endswith(".py") and file != '__init__.py':

我使用了一个非常简单的命名约定(即 file_name = FileName),因此基于处理程序目录中的文件,我可以为每个动态创建路由。

我在应该路由的方法上使用装饰器(即 url 处理程序/方法将转到处理程序文件,处理程序类和 Handler.Method 将被调用)。所以我得到了每个类的所有方法,如果类方法具有装饰器创建的属性,则路由它!

所以像这样的for循环:

methods = inspect.getmembers(handlercls, predicate=inspect.ismethod)
methods = [x[1] for x in methods if hasattr(x[1], 'route')]

for method in methods:
    # Set some kwargs that I can then pass to a route (i.e. handler path, method to call, etc...)

就像我说的,可能为什么没有人回答这个问题,整个解决方案很长,所以如果有人想要,我会把它放在 GitHub 上,也许人们可以添加/控制。对它进行改进。

于 2013-03-17T21:19:46.850 回答