【问题标题】:How to give always 1 file with tornado.web.StaticFileHandler?如何使用 tornado.web.StaticFileHandler 始终提供 1 个文件?
【发布时间】:2021-07-11 13:29:00
【问题描述】:

我需要对任何 GET 请求使用 1 张图片进行响应。

def make_app():
    return tornado.web.Application([
        (r"/", ItWorks),
        (r"/logme", MarkerCatchHandler),
        (r"/(robots.\txt)",tornado.web.StaticFileHandler, {"path": "./robots.txt"}),
        (r"/images/(.*)",tornado.web.StaticFileHandler, {"path": "./images/1.png"}),
        (r"/testme/(.*)",tornado.web.StaticFileHandler, {"path": "./images", "default_filename": "1.png"}),
        ],debug=True)

if __name__ == "__main__":
    app = make_app()
    app.listen(8888, address = domain_name)
    tornado.ioloop.IOLoop.current().start()

使用 http://localhost:8888/testme/3.png 我得到 404 错误

【问题讨论】:

  • 顺便说一句,当我问localhost:8888/robots.txt 我得到了同样的错误 - 404
  • 重写StaticFileHandler的get方法。

标签: python python-3.x tornado


【解决方案1】:

如果您想提供单个文件,您需要将文件夹的名称作为path 传递。记住不要传递文件名。

# this will serve robots.txt from the current directory
(r"/(robots\.txt)",tornado.web.StaticFileHandler, {"path": "./"}),

# this will only serve 1.png from the images directory
(r"/images/1.png",tornado.web.StaticFileHandler, {"path": "./images"}),

# this will serve all images in the images directory
(r"/testme/(.*)",tornado.web.StaticFileHandler, {"path": "./images"),

【讨论】:

  • 我需要为不同的请求返回相同的文件。例如,当用户请求 /data/1.png 或 /data/2.png 或 data/3.png 时,即使文件不存在,我也必须始终返回相同的文件。我该怎么做?
【解决方案2】:

我建议您扩展提供的StaticFileHandler 并覆盖get_absolute_path(确保使用@classmethod 装饰器)始终只使用根目录并忽略路径。

类似:

import os
import tornado.web

class SingleFileHandler(tornado.web.StaticFileHandler):
    @classmethod
    def get_absolute_path(cls, root: str, path: str) -> str:
        abspath = os.path.abspath(root)
        return abspath

app = tornado.web.Application([
    (r"/(.*)", SingleFileHandler, {"path": "./images/always.png"}),
])
app.listen(8888)
tornado.ioloop.IOLoop.current().start()

从技术上讲,如果需要优化,您还可以覆盖 validate_absolute_path 以仅返回传递的 absolute_path

如果您将让其他人使用此类,则进行一些配置检查是有意义的 - 例如,如果传递的 root 实际上是您可以/愿意提供以防止用户配置错误的文件。

【讨论】:

    猜你喜欢
    • 2014-10-12
    • 2021-09-18
    • 1970-01-01
    • 1970-01-01
    • 2020-07-20
    • 1970-01-01
    • 2016-09-26
    • 1970-01-01
    • 2011-01-08
    相关资源
    最近更新 更多