下载龙卷风Web服务器提供的文件

时间:2016-01-13 21:22:35

标签: python tornado

这就是我目前定义龙卷风网络服务器的方式:

application = tornado.web.Application([
    tornado.web.url(r"/server", MainHandler),
    tornado.web.url(r"/(.*)", tornado.web.StaticFileHandler, { "path": scriptpath,  "default_filename": "index.html" }),
])

index.html是基于网络的gui的起始页面。它将通过http:/// server与后端服务器通信,gui对服务器的请求由MainHandler函数处理。

目录结构如下:

root_directory/
    server.py
    fileiwanttodownload.tar.gz
    index.html

我希望能够输入浏览器:

的http:///data/fileiwanttodownload.tar.gz

并将文件作为常规文件下载发送给我。

我试图做的是:

application = tornado.web.Application([
    tornado.web.url(r"/server", MainHandler),
    tornado.web.url(r"/data", tornado.web.StaticFileHandler, { "path": scriptpath } ),
    tornado.web.url(r"/(.*)", tornado.web.StaticFileHandler, { "path": scriptpath,  "default_filename": "index.html" }),
])

但是,由于原因对于那些知道答案的人来说可能是显而易见的,所以这不起作用。

我唯一的线索是以下错误消息:

Uncaught exception GET /data (192.168.4.168)
HTTPServerRequest(protocol='http', host='192.168.4.195:8888', method='GET', uri='/data', version='HTTP/1.1', remote_ip='192.168.4.168', headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9', 'Host': '192.168.4.195:8888', 'Accept-Encoding': 'gzip, deflate', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Connection': 'keep-alive', 'Accept-Language': 'en-us'})
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/tornado/web.py", line 1445, in _execute
    result = yield result
  File "/usr/local/lib/python3.4/dist-packages/tornado/gen.py", line 1008, in run
    value = future.result()
  File "/usr/local/lib/python3.4/dist-packages/tornado/concurrent.py", line 232, in result
    raise_exc_info(self._exc_info)
  File "<string>", line 3, in raise_exc_info
  File "/usr/local/lib/python3.4/dist-packages/tornado/gen.py", line 267, in wrapper
    result = func(*args, **kwargs)
TypeError: get() missing 1 required positional argument: 'path'

1 个答案:

答案 0 :(得分:2)

scriptpath你还没有表现出来,可能是错的。在path中,您应该为文件提供根目录,在URI匹配器中仅捕获文件左右。简单的例子:

import tornado.ioloop
import tornado.web
import os

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

def make_app():
    script_path = os.path.dirname(__file__)
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/data/(.*)", tornado.web.StaticFileHandler, {"path": script_path}),
        #         ^ we capture only this part
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

您可以运行它,但建议将静态/数据文件存储在单独的目录中,因为可以从应用程序根目录下载所有内容,包括python one。

请将您的可下载文件放入,例如在data子目录中,然后

script_path = os.path.join(os.path.dirname(__file__), 'data')

有关StaticFileHandler的更多信息。

修改

您收到的错误是因为您的代码/data路由中包含StaticFileHandler,但未从请求的路径捕获()