Skip to main content
 首页 » 编程设计

python之从 Tornado Python 中的 RequestHandler 访问 URL

2024年11月01日11lautakyan007

在我的 super 简单的 Tornado URL 调度程序中:

import tornado.ioloop 
import tornado.web 
 
class MainHandler(tornado.web.RequestHandler): 
    def get(self): 
        self.write("Main MainHandler ") 
 
class MainHandler1(tornado.web.RequestHandler): 
    def get(self): 
        self.write("Main MainHandler 1") 
 
class api_v1(tornado.web.RequestHandler): 
    def get(self): 
        pass 
 
 
if __name__ == "__main__": 
    application = tornado.web.Application(handlers=[ 
        (r"/", MainHandler), 
        (r"/main1/", MainHandler1), 
        #Meta API from the Application URIs 
        (r"/api/v1/", api_v1), 
    ]) 
 
 
    application.listen(8888) 
    tornado.ioloop.IOLoop.instance().start() 

如何从 class api_v1(tornado.web.RequestHandler) 访问 handlers 变量。可能吗?

我想在用户访问 http://.../api/v1/ 时显示 URLS 模式

提前致谢。

请您参考如下方法:

传递给 Application 构造函数的处理程序表在事后不可用。相反,在创建应用程序之前保存一份副本并使其可供处理程序使用:

handlers = [...] 
# Unrecognized keyword arguments end up in Application.settings; recognized ones 
# get eaten.  Pass the handler table in twice, once for the Application itself 
# and once for settings. 
app = Application(handlers, handler_table=handlers) 

并在处理程序中使用 self.settings['handler_table']