Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python tornado服务器提供一个文件_Python_Webserver_Tornado - Fatal编程技术网

Python tornado服务器提供一个文件

Python tornado服务器提供一个文件,python,webserver,tornado,Python,Webserver,Tornado,我知道如何为静态文件/PNG等提供服务,只要它们保存在某个web静态路径下 如何在路径(例如/usr/local/data/table.csv)上提供文件 另外,我想知道是否可以显示页面结果(分页),但我更关心的是提供任意位置的文件,即使我从本地删除它们(我的意思是一旦上传/缓存),它们也会保留下来。[这可能是一个单独的问题]在最基本的层面上,您需要读取文件并将其写入响应: import os.path from mimetypes import guess_type import torna

我知道如何为静态文件/PNG等提供服务,只要它们保存在某个web静态路径下

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


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

在最基本的层面上,您需要读取文件并将其写入响应:

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()
(免责声明。这是一个快速编写程序,几乎肯定不会在所有情况下都起作用,所以要小心。)