Search code examples
python-2.7tornado

How can I customize header for static file on tornado server?


When I request to favicon.ico located on the static dir, the tornado server responses with Server Header(Server:TornadoServer/4.4.2). I want to hide server name and version. How can I modify it?

class Application(tornado.web.Application):
    def __init__(self):
        handlers = [
            (r"/", HomeHandler),
            (r".*", BaseHandler),
        ]
        settings = dict(
            template_path=os.path.join(os.path.dirname(__file__), "templates"),
            static_path=os.path.join(os.path.dirname(__file__), "static"),
            debug=True,
        )

I could hide the Server Header on the normal contents by this.

class BaseHandler(tornado.web.RequestHandler):
    @property
    def set_default_headers(self):
        self.set_header("Server", "hidden")

Solution

  • Tornado allows to change the default static handler class with static_handlr_class option in settings

    import os
    import tornado.ioloop
    import tornado.web
    
    
    class HomeHandler(tornado.web.RequestHandler):
    
        def get(self):
            self.write('ok')
    
    class Application(tornado.web.Application):
        def __init__(self):
            handlers = [
                (r"/", HomeHandler),
            ]
            settings = dict(
                template_path=os.path.join(os.path.dirname(__file__), "templates"),
                static_path=os.path.join(os.path.dirname(__file__), "static"),
                static_handler_class=MyStaticFileHandler,
                debug=True,
            )
            super(Application, self).__init__(handlers, **settings)
    
    class MyStaticFileHandler(tornado.web.StaticFileHandler):
    
        def set_default_headers(self):
            self.set_header("Server", "hidden")
    
    if __name__ == "__main__":
        application = Application()
        application.listen(8888)
        tornado.ioloop.IOLoop.current().start()