Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't get tornado staticfilehandler to work

Tags:

python

tornado

Why doesn't this work:

application = tornado.web.Application([(r"/upload.html",tornado.web.StaticFileHandler,\
                                        {"path":r"../web/upload.html"}),])    
if __name__ == "__main__":
    print "listening"
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

Hitting

http://localhost:8888/upload.html throws:

TypeError: get() takes at least 2 arguments (1 given)
ERROR:tornado.access:500 GET /upload.html (::1) 6.47ms 

I have tried to search across the internet but it seems like my usage is totally correct. So I can't find why it is not working. Most of the examples on the internet are about giving a static handler for a complete directory. So is it the case, that it does not work for individual files?

like image 275
Captain Jack sparrow Avatar asked Feb 14 '23 15:02

Captain Jack sparrow


2 Answers

You have two options to fix this error.

  1. Add all the files of the ../web/ directory. Tornado does not handle single files.

    application = tornado.web.Application([(r"/(.*)", \
                                           tornado.web.StaticFileHandler, \
                                           {"path":r"../web/"}),]) 
    
  2. You can render the HTML passing a file as input. You need to create a handler for each HTML file.

    import tornado.web
    import tornado.httpserver
    
    
    class Application(tornado.web.Application):
        def __init__(self):
            handlers = [
                (r"/upload.html", MainHandler)
            ]
            settings = {
                "template_path": "../web/",
            }
            tornado.web.Application.__init__(self, handlers, **settings)
    
    
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.render("upload.html")
    
    
    def main():
        applicaton = Application()
        http_server = tornado.httpserver.HTTPServer(applicaton)
        http_server.listen(8888)
    
        tornado.ioloop.IOLoop.instance().start()
    
    if __name__ == "__main__":
        main() 
    
like image 195
jcfaracco Avatar answered Apr 06 '23 23:04

jcfaracco


StaticFileHandler is usually used to serve a directory, and as such it expects to receive a path argument. From the docs:

Note that a capture group in the regex is required to parse the value for the path argument to the get() method (different than the constructor argument above); see URLSpec for details.

e.g.

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

will serve every file in ../web, including upload.html.

like image 22
Cole Maclean Avatar answered Apr 06 '23 21:04

Cole Maclean