Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a better way to handle index.html with Tornado?

Tags:

python

tornado


I want to know if there is a better way to handle my index.html file with Tornado.

I use StaticFileHandler for all the request,and use a specific MainHandler to handle my main request. If I only use StaticFileHandler I got a 403: Forbidden error

GET http://localhost:9000/
WARNING:root:403 GET / (127.0.0.1):  is not a file

here how I doing now:

import os
import tornado.ioloop
import tornado.web
from  tornado import web

__author__ = 'gvincent'

root = os.path.dirname(__file__)
port = 9999

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        try:
            with open(os.path.join(root, 'index.html')) as f:
                self.write(f.read())
        except IOError as e:
            self.write("404: Not Found")

application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/(.*)", web.StaticFileHandler, dict(path=root)),
    ])

if __name__ == '__main__':
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()
like image 797
Guillaume Vincent Avatar asked Jan 17 '13 17:01

Guillaume Vincent


People also ask

What is Python Tornado used for?

Tornado is a Python web framework and asynchronous network library, originally developed at FriendFreed. Tornado uses non-blocking network-io. Due to this, it can handle thousands of active server connections. It is a saviour for applications where long polling and a large number of active connections are maintained.

What is tornado programming?

Tornado is a scalable, non-blocking web server and web application framework written in Python. It was developed for use by FriendFeed; the company was acquired by Facebook in 2009 and Tornado was open-sourced soon after.


2 Answers

Turns out that Tornado's StaticFileHandler already includes default filename functionality.

Feature was added in Tornado release 1.2.0: https://github.com/tornadoweb/tornado/commit/638a151d96d681d3bdd6ba5ce5dcf2bd1447959c

To specify a default file name you need to set the "default_filename" parameter as part of the WebStaticFileHandler initialization.

Updating your example:

import os
import tornado.ioloop
import tornado.web

root = os.path.dirname(__file__)
port = 9999

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

if __name__ == '__main__':
    application.listen(port)
    tornado.ioloop.IOLoop.instance().start()

This handles root requests:

  • / -> /index.html

sub-directory requests:

  • /tests/ -> /tests/index.html

and appears to correctly handle redirects for directories, which is nice:

  • /tests -> /tests/index.html
like image 167
Adaptation Avatar answered Oct 13 '22 00:10

Adaptation


Thanks to the previous answer, here is the solution I prefer:

import Settings
import tornado.web
import tornado.httpserver


class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", MainHandler)
        ]
        settings = {
            "template_path": Settings.TEMPLATE_PATH,
            "static_path": Settings.STATIC_PATH,
        }
        tornado.web.Application.__init__(self, handlers, **settings)


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render("index.html")


def main():
    applicaton = Application()
    http_server = tornado.httpserver.HTTPServer(applicaton)
    http_server.listen(9999)

    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    main()

And Settings.py

import os
dirname = os.path.dirname(__file__)

STATIC_PATH = os.path.join(dirname, 'static')
TEMPLATE_PATH = os.path.join(dirname, 'templates')
like image 20
Guillaume Vincent Avatar answered Oct 13 '22 01:10

Guillaume Vincent