有没有人想出一种优雅的方式在Google App Engine中实现自动路由?我最终得到了一个非常长的路由列表,即
urls = routes.HandlerPrefixRoute(h+'index_handler.',[RedirectRoute(r'/',handler='IndexHandler')]),...我想让example.com/blog自动路由到博客处理程序,example.com/ blog /method自动路由到blog.method方法。
发布于 2013-03-18 05:19:47
我已经想出了一个使用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上,也许人们可以添加/控制。对它进行改进。
https://stackoverflow.com/questions/15416863
复制相似问题