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()
Thanks to the previous answer, here is the solution I prefer:
And Settings.py
I have been trying this. Don't use render it has additional overhead of parsing templates and gives error on template type strings in static html. I found this is the simplest way. Tornado is looking for a capturing parenthesis in regex , just give it an empty capturing group.
This has effect of resolving / to index.html and also avoid unwanted resolves like /views.html to static_dir/views.html
This worked for me From the tornado docs:
There is no need to explicitly add a
StaticFileHandler
; just specify the static_path and it will serve those pages.You are correct that you need a MainHandler, as for some reason Tornado will not serve the
index.html
file, even if you append the filename to the URL.In that case, this slight modification to your code should work for you:
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:
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
Use this code instead
now use that class instead of vanilla StaticFileHandler in your Application... job's done!