【问题标题】:Access to URLs from a RequestHandler in Tornado Python从 Tornado Python 中的 RequestHandler 访问 URL
【发布时间】:2023-03-19 14:06:02
【问题描述】:

在我的超简单 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 模式

提前致谢。

【问题讨论】:

    标签: python class handler tornado multiple-inheritance


    【解决方案1】:

    传递给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']

    【讨论】:

      【解决方案2】:

      这是一个小技巧,因为它使用私有方法 Application._get_host_handlers,但该方法多年来没有改变,因此它可能是安全的:

      class api_v1(tornado.web.RequestHandler):
          def get(self):
              handlers = self.application._get_host_handlers(self.request)
              response = json.dumps([spec.regex.pattern for spec in handlers])
              self.finish(response)
      

      【讨论】:

      • 它已经有一段时间没有改变了,但我一直想尝试将顺序正则表达式匹配更改为 '(%s)' % ')|('.join(re.escape(spec.regex.pattern) for spec in handlers)) 之类的东西(棘手的部分是处理输入正则表达式中的捕获组) .
      猜你喜欢
      • 2017-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多