如何使用tornado.web.StaticFileHandler始终提供1个文件?

2024-05-19 09:15:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在任何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个错误


Tags: pathname图像txtwebappgetmake
2条回答

如果要为单个文件提供服务,则需要将文件夹的名称传递为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"),

我建议您扩展提供的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实际上是一个你可以/愿意用来防止用户配置错误的文件

相关问题 更多 >

    热门问题