ehsan shirzadi
ehsan shirzadi

Reputation: 4859

Python tornado global variables

I have a Python Tornado application. I want to have variables which are shared across multiple files. previously I used to declare and initiate them in a python file name global.py and import it into other files. this was a good idea until some of my variables needs to query from database, so every time I imported global.py to get just one value, all of queries was running and causes to slow down my application.
The next step was that I defined my variables in tornado start.py like this:

class RepublishanApplication(tornado.web.Application):

    def __init__(self):
        ##################################################
        # conn = pymongo.Connection("localhost", 27017)
        self.Countries = GlobalDefined.Countries
        self.Countries_rev = GlobalDefined.Countries_rev
        self.Languages = GlobalDefined.Languages
        self.Categories = GlobalDefined.Categories
        self.Categories_rev = GlobalDefined.Categories_rev
        self.NewsAgencies   = GlobalDefined.NewsAgencies
        self.NewsAgencies_rev = GlobalDefined.NewsAgencies_rev
        self.SharedConnections = SharedConnections

I can access these variables in handlers like this:

self.application.Countries 

It's working good. but the problem is that I can access to these variables only in handler classes and if I want to access them, I have to pass them to functions. I think it's not a good idea. Do you have any suggestion to have access to these variable every where without having to pass application instance to all of my functions or even another way to help me?

Upvotes: 1

Views: 3503

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24009

Putting your global variables in a globals.py file is a fine way to accomplish this. If you use PyMongo to query values from MongoDB when globals.py is imported, that work is only done the first time globals.py is imported in a process. Other imports of globals.py get the module from the sys.modules cache.

Upvotes: 3

Related Questions