简体   繁体   English

Python龙卷风全局变量

[英]Python tornado global variables

I have a Python Tornado application. 我有一个Python Tornado应用程序。 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. 以前,我曾经在Python文件名global.py中声明并启动它们,然后将其导入其他文件。 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. 在需要从数据库查询某些变量之前,这是一个好主意,因此,每当我导入global.py来获取一个值时,所有查询都在运行,从而导致我的应用程序运行缓慢。
The next step was that I defined my variables in tornado start.py like this: 下一步是我在龙卷风start.py中定义我的变量,如下所示:

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? 您是否有建议在任何地方都可以访问这些变量,而不必将应用程序实例传递给我的所有函数,甚至不需要其他方法来帮助我?

Putting your global variables in a globals.py file is a fine way to accomplish this. 将全局变量放在globals.py文件中是完成此操作的一种好方法。 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. 如果在导入globals.py时使用PyMongo从MongoDB查询值,则该工作仅在首次在进程中导入globals.py时完成。 Other imports of globals.py get the module from the sys.modules cache. 其他导入的globals.py从sys.modules缓存中获取模块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM