How can Tornado serve a single static file at an arbitrary location?

这一生的挚爱 提交于 2019-12-04 02:40:42

Something like this should work:

import os
import tornado.ioloop
import tornado.web


class MyFileHandler(tornado.web.StaticFileHandler):
    def initialize(self, path):
        self.dirname, self.filename = os.path.split(path)
        super(MyFileHandler, self).initialize(self.dirname)

    def get(self, path=None, include_body=True):
        # Ignore 'path'.
        super(MyFileHandler, self).get(self.filename, include_body)

app = tornado.web.Application([
    (r'/foo\.json', MyFileHandler, {'path': '/path/to/foo.json'})
])

app.listen(8888)
tornado.ioloop.IOLoop.current().start()

The URL pattern and the filename need not be related, you could do this and it would work just as well:

app = tornado.web.Application([
    (r'/jesse\.txt', MyFileHandler, {'path': '/path/to/foo.json'})
])

StaticFileHandler expects two arguments, so if you want a single url (/foo.json) to be mapped to your file path you can use:

app = tornado.web.Application([
(r'/foo.json()', tornado.web.StaticFileHandler, {'path': '/path/to/foo.json'})
])

The regex will match /foo.json and send the empty capture group (), which will cause the filepath to be used as is. When the capture group is not empty, /path/to/foo.json will be treated as a directory /path/to/foo.json/, and the handler will try to match whatever is within the capture group to a file name in that directory.

StaticFileHandler gets is file name from the regex capturing group and the directory name from its path argument. It will work if you use /path/to/ as the path:

(r'/(foo\.json)', tornado.web.StaticFileHandler, {'path': '/path/to/'})

StaticFileHandler is designed for cases where URLs and filenames match; if you can't arrange to have this file available on disk under the same name you want to serve it as you'll have to use a custom handler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!