首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何用tornado.web.StaticFileHandler始终给出1个文件?

如何用tornado.web.StaticFileHandler始终给出1个文件?
EN

Stack Overflow用户
提问于 2021-07-11 21:29:01
回答 2查看 48关注 0票数 0

我需要在任何GET请求上响应一个图像。

代码语言:javascript
复制
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错误

EN

回答 2

Stack Overflow用户

发布于 2021-07-13 13:00:27

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

代码语言:javascript
复制
# 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"),
票数 0
EN

Stack Overflow用户

发布于 2021-08-22 18:20:32

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

类似于:

代码语言:javascript
复制
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实际上是一个你可以/愿意用来防止用户配置错误的文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68336692

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档