无法获取龙卷风静态文件手

2024-06-16 14:48:41 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么这不起作用:

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

打击

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 

我试过在网上搜索,但似乎我的用法完全正确。 所以我找不到它为什么不起作用。internet上的大多数示例都是关于为完整目录提供静态处理程序的。那么是这样吗,它不适用于单独的文件?


Tags: pathnamewebhttpifserverapplicationmain
3条回答

StaticFileHandler通常用于为目录提供服务,因此它希望接收一个path参数。来自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.

例如

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

将为../web中的每个文件提供服务,包括upload.html。

有两个选项可以修复此错误。

  1. 添加../web/目录的所有文件。Tornado不处理单个文件。

    application = tornado.web.Application([(r"/(.*)", \
                                           tornado.web.StaticFileHandler, \
                                           {"path":r"../web/"}),]) 
    
  2. 您可以将传递文件的HTML呈现为输入。您需要为每个HTML文件创建一个处理程序。

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

试试这个:

application = tornado.web.Application([(r"/upload.html",tornado.web.StaticFileHandler,\
                                   {"path":r"../web"},'default_filename':'upload.html'),])  

相关问题 更多 >