Skip to main content
 首页 » 编程设计

python之为什么字典有时是空的 (在 tornado.web.Application 类实例中保存数据)

2025年05月04日10grandyang

我正在尝试在 Tornado 中的请求之间传递一些数据。我有一个名为 tcp_con 的变量。

class Application( tornado.web.Application ): 
    def __init__( self, **overrides ): 
        handlers = [ 
            ( r"/", hd.MainHandler ), 
 
            ] 
 
        settings = { "cookie_secret": "thisismysecret", 
                    "login_url": "/auth/login", 
                    "template_path":  os.path.join( os.path.dirname( __file__ ), "templates" ), 
                    "static_path": os.path.join( os.path.dirname( __file__ ), "static" ), 
                    "xsrf_cookies": True 
                    } 
 
        # Initializing variables         
        self.debug = overrides['debug'] 
        self.__is_running_checks = False 
        self.tcp_con = {} 
        self.queue = Queue.Queue() 

我在用户提交表单时填充了一些变量,但是当我刷新页面时 tcp_con 变量为空,如果我再次刷新然后字典又包含数据,所以有时这些值在字典中,有时不在。可能是什么问题?

这是请求句柄的一部分:

@tornado.web.authenticated  
def get( self ): 
    """ 
    """                     
    print self.application.tcp_con 

请您参考如下方法:

您的服务器上很可能有不止一个 Tornado 进程。每个进程都有自己的 Application 类。根据要求,您可以获得来自不同流程的响应。因此,您不能使用此类来保存应用程序的状态。

来自 Tornado 文档 ( class tornado.tcpserver.TCPServer ):

start(num_processes=1) 

Starts this server in the IOLoop.

By default, we run the server in this process and do not fork any additional child process.

If num_processes is None or <= 0, we detect the number of cores available on this machine and fork that number of child processes. If num_processes is given and > 1, we fork that specific number of sub-processes.

Since we use processes and not threads, there is no shared memory between any server code.