Sumit Khanna
Sumit Khanna

Reputation: 81

tornado server serve a file

I know how to serve static files / pngs etc far as they are kept under some web static path.

How do I go about serving a file at the path, say /usr/local/data/table.csv ?

Also, I was wondering if I could display the page wise results(pagination) but I am more concerned about serving arbitrary location files + they stay even if I remove them from the local (I mean once uploaded / cached). [that could be a separate ques though]

Upvotes: 4

Views: 2597

Answers (1)

Berislav Lopac
Berislav Lopac

Reputation: 17273

On the most basic level, you need to read your file and write it to the response:

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

(Disclaimer. This is a quick writeup, it almost certainly won't work in all cases, so be careful.)

Upvotes: 4

Related Questions