我需要在任何GET请求上响应一个图像。
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错误
发布于 2021-07-13 13:00:27
如果您想提供单个文件,则需要将文件夹的名称作为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"),发布于 2021-08-22 18:20:32
我建议您扩展提供的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实际上是一个你可以/愿意用来防止用户配置错误的文件。
https://stackoverflow.com/questions/68336692
复制相似问题