龙卷风服务器服务文件

时间:2016-11-05 19:07:39

标签: python webserver tornado

我知道如何提供静态文件/ png等,因为它们保存在某些Web静态路径下。

如何在路径上提供文件,例如/usr/local/data/table.csv?

另外,我想知道我是否可以显示页面明智的结果(分页),但我更关心提供任意位置文件+即使我从本地删除它们也会保留(我的意思是一旦上传/缓存)。 [虽然可能是一个单独的问题]

1 个答案:

答案 0 :(得分:1)

在最基本的层面上,您需要阅读文件并将其写入回复:

import os.path
from mimetypes import guess_type

import tornado.web
import tornado.httpserver

BASEDIR_NAME = os.path.dirname(__file__)
BASEDIR_PATH = os.path.abspath(BASEDIR_NAME)

FILES_ROOT = os.path.join(BASEDIR_PATH, 'files')


class FileHandler(tornado.web.RequestHandler):

    def get(self, path):
        file_location = os.path.join(FILES_ROOT, path)
        if not os.path.isfile(file_location):
            raise tornado.web.HTTPError(status_code=404)
        content_type, _ = guess_type(file_location)
        self.add_header('Content-Type', content_type)
        with open(file_location) as source_file:
            self.write(source_file.read())

app = tornado.web.Application([
    tornado.web.url(r"/(.+)", FileHandler),
])

http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(8080, address='localhost')
tornado.ioloop.IOLoop.instance().start()

(免责声明。这是一个快速的文章,它几乎肯定不会在所有情况下都有效,所以要小心。)

相关问题