【问题标题】:How to serve static files from a different directory than the static path?如何从与静态路径不同的目录提供静态文件?
【发布时间】:2023-05-19 04:52:01
【问题描述】:

我正在尝试这个:

favicon_path = '/path/to/favicon.ico'

settings = {'debug': True, 
            'static_path': os.path.join(PATH, 'static')}

handlers = [(r'/', WebHandler),
            (r'/favicon.ico', tornado.web.StaticFileHandler, {'path': favicon_path})]

application = tornado.web.Application(handlers, **settings)
application.listen(port)
tornado.ioloop.IOLoop.instance().start()

但它继续为我的 static_path 中的favicon.ico 提供服务(如上所述,我在两个不同的路径中有两个不同的favicon.ico,但我希望能够覆盖@987654324 中的那个@)。

【问题讨论】:

    标签: python static tornado favicon


    【解决方案1】:

    从应用设置中删除static_path

    然后将您的处理程序设置为:

    handlers = [
                (r'/(favicon\.ico)', tornado.web.StaticFileHandler, {'path': favicon_path_dir}),
                (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': static_path_dir}),
                (r'/', WebHandler)
    ]
    

    【讨论】:

    • 好的,我通过将其更改为 r'/(favicon\.ico)' 来实现它。为什么这行得通? (我从文档中的类似示例中复制了它。)
    • 似乎在应用设置中设置 static_path 对 favicon 和 robots.txt 有特殊情况。来自文档:we will serve /favicon.ico and /robots.txt from the same [static_path] directory
    • @shino 它起作用了,因为 r'/favicon.ico' 是一个正则表达式,并且您正确地转义了 '.'
    • 好吧,它仍然会匹配文字“。”。起作用的原因是匹配的正则表达式组作为参数传递给RequestHandler 的方法。预制的StaticFileHandler 类期望它正在查找的文件的路径相对于处理程序类上的“static_path”设置或“path”成员。 {'path': static_path} get 传递给处理程序 initialize 方法,然后在实例上设置它。
    • @shino 你需要提取一组文件名来服务,我猜。正则表达式中的括号就是这样做的。尝试删除它,它会告诉你TypeError: get() missing 1 required positional argument: 'path',但我没有测试它。
    【解决方案2】:

    您需要将 favicon.ico 用括号括起来并转义正则表达式中的句点。你的代码会变成

    favicon_path = '/path/to/favicon.ico' # Actually the directory containing the favicon.ico file
    
    settings = {
        'debug': True, 
        'static_path': os.path.join(PATH, 'static')}
    
    handlers = [
        (r'/', WebHandler),
        (r'/(favicon\.ico)', tornado.web.StaticFileHandler, {'path': favicon_path})]
    
    application = tornado.web.Application(handlers, **settings)
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()
    

    【讨论】:

      【解决方案3】:

      有两种方法。

      1。在设置中使用 static_url_prefix

      例如

      settings = dict(
          static_path=os.path.join(os.path.dirname(__file__), 'static'),
          static_url_prefix="/adtrpt/static/",
      )
      

      2。使用自定义处理程序

      将自定义处理程序附加到处理程序

      handlers.append((r"/adtrpt/static/(.*)", MyStaticFileHandler, {"path": os.path.join(os.path.dirname(__file__), 'static')}))
      

      然后实现您的自定义方法。

      class StaticHandler(BaseHandler):
          def get(self):
              path = self.request.path
              print(path)
              self.redirect(BASE_URI + path)
      

      【讨论】: