Tornado 如何在任意位置提供单个静态文件? [英] How can Tornado serve a single static file at an arbitrary location?
问题描述
我正在使用 Tornado 开发一个简单的网络应用程序.它提供一些动态文件和一些静态文件.动态文件不是问题,但我无法提供静态文件.我要做的是在访问/foo.json URL 时提供文件/path/to/foo.json.
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 file. What I am looking to do is to serve the file /path/to/foo.json when the /foo.json URL is accessed.
请注意/path/to/foo.json 位于文档根目录之外.在 Apache 中,我只会设置一个别名.我有龙卷风:
Note that /path/to/foo.json is outside the document root. In Apache I would just set up an Alias. With Tornado I have:
app = tornado.web.Application([
(r'/dynamic\.html', MyService, dict(param = 12345)),
(r'/(foo\.json)', tornado.web.StaticFileHandler, {'path': '/path/to/foo.json'})
])
我添加了正则表达式组运算符 ()
以满足 Tornado,否则会引发异常.但是现在,当我访问/foo.json 时,出现 404: File Not Found.
I added the regex group operator ()
to satisfy Tornado, which threw an exception otherwise. But now, when I access /foo.json, I get a 404: File Not Found.
测试显示 Tornado 试图使用提供的路径作为根目录,并附加 foo.json,这意味着如果我的文件位于/path/to/foo.json/foo.json,则可以找到它.接近,但不完全.
Tests reveal that Tornado is attempting to use the path provided as a root directory to which it appends foo.json, implying my file could be found if it were at /path/to/foo.json/foo.json. Close, but not quite.
我想我可以将我的路径缩短为简单的/path/to",这将在/foo.json URL 上触发/path/to/foo.json 的获取,但这迫使我使用相同的名称在文件系统上的 URL 中.我怎样才能做一个简单的、任意的、URL 到文件的映射?
I suppose I could shorten my path to simply "/path/to", which will trigger a fetch of /path/to/foo.json upon the /foo.json URL, but this forces me to use the same name in the URL as on the filesystem. How can I just do a simple, arbitrary, URL to file mapping?
我对此做了一些研究,阅读了 的文档tornado.web.Application 和 tornado.web.StaticFilehandler,加上一些 其他 SO 问题.没有什么是我的用例.
I have done some research on this, reading the documentation for tornado.web.Application and tornado.web.StaticFilehandler, plus some other SO questions. Nothing is quite my use case.
推荐答案
这样的事情应该可行:
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()
URL 模式和文件名不需要相关,你可以这样做,它也能正常工作:
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'})
])
这篇关于Tornado 如何在任意位置提供单个静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!