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

前端 未结 3 1635
忘掉有多难
忘掉有多难 2021-02-14 12:50

I am developing a simple web app with Tornado. It serves some dynamic files and some static ones. The dynamic ones are not a problem, but I am having trouble serving a static fi

3条回答
  •  生来不讨喜
    2021-02-14 13:36

    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'})
    ])
    

提交回复
热议问题