2016-11-05 103 views
0

我知道如何提供静态文件/ PNG等,因为它们被保存在一些网络静态路径下。龙卷风服务器提供文件

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

另外,我在想,如果我可以显示的页面明智的结果(分页),但我更关心的是服务于任意位置的文件+他们留即使我从本地删除(我的意思是,一旦上传/缓存)。 [这可能是一个独立的疑问句虽然]

回答

0

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

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() 

(免责声明这是一个快速的书面记录,它几乎肯定不会在所有情况下工作,所以要小心。)