1

I have the base class:

class BaseGameHandler(BaseRequestHandler):
    name = 'Base'
    def get(self):
        self.render(self.name + ".html")

Now, I need to define a few subclasses of this but the thing is, they have to have a decorator. Equivalent code would be:

@route('asteroid')
class AsteroidGameHandler(BaseGameHandler):
    name = 'asteroid'


@route('blah')
class BlahGameHandler(BaseGameHandler):
    name = 'blah'

and maybe a few more. A little background here: This is a tornado web app and the @route decorator allows you to map /blah to BlahGameHandler. This code maps /blah to BlahGameHandler and /asteroid to AsteroidGameHandler.

So I thoughtI should use metaprogramming in python and define all these classes on the fly. I tried the following which doesn't work(and by doesn't work I mean the final web-app throws 404 on both /asteroid and /blah):

game_names = ['asteroid', 'blah']

games = list([game, type('%sGameHandler' % (game.title()), (BaseGameHandler,), {'name': game})] for game in game_names)

for i in xrange(len(games)):
    games[i][1] = route(games[i][0])(games[i][1])

What am I missing? Aren't these two codes equivalent when run?

4

1 回答 1

0

您使用的库仅在您的模块中查找全局类对象。

将每个类设置为全局;该globals()函数使您可以将模块命名空间作为字典访问:

for i in xrange(len(games)):
    globals()[games[i][1].__name__] = route(games[i][0])(games[i][1])

include()代码不会列表中查找您的视图。

具体来说,include()使用以下循环来检测处理程序:

for member in dir(module):
    member = getattr(module, member)
    if isinstance(member, type) and issubclass(member, web.RequestHandler) and hasattr(member, 'routes'):
        # ...
    elif isinstance(member, type) and issubclass(member, web.RequestHandler) and hasattr(member, 'route_path'):
        # ...
    elif isinstance(member, type) and issubclass(member, web.RequestHandler) and hasattr(member, 'rest_route_path'):
        # ...

dir(module)只考虑顶级对象。

于 2013-07-01T11:13:31.710 回答