Q:

How not to call initialize at each request with Tornado

I want to set variables when starting my Tornado webserver, so I tried to override initialize on my RequestHandler class. But apparently, initialize is launched each time a request is made, according to the following code and its output:
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def initialize(self):
        print("Launching initialization...")

    def get(self):
        print("Get: {}{}".format(self.request.host, self.request.uri))

app = tornado.web.Application([=
    (r"/.*", MainHandler)
])

def runserver():
    import tornado.ioloop

    app.listen(8080)
    tornado.ioloop.IOLoop.instance().start()

if __name__ == "__main__":
    runserver()

stdout:
~ ➤ ./redirector.py
Launching initialization...
Get: 127.0.0.1:8080/
Launching initialization...
Get: 127.0.0.1:8080/favicon.ico
Launching initialization...
Get: 127.0.0.1:8080/favicon.ico
Launching initialization...
Get: 127.0.0.1:8080/

This behavior is the complete contrary to what is written in the doc:

Hook for subclass initialization.

(Meaning it is called at the end of __init__)
So, does anybody know how to do what I want to ?
Thanks in advance.

A:

It's not contrary to the doc; have a look at the Structure of a Tornado app section. A RequestHandler object is created for each request.
If you want code to be executed when the app is started only, subclass the Application class and override __init__, or just put it in your runserver function.

