[英]How do I use a global variable in cherrypy?
I need to access a global variable that keeps its state over diffferent server requsts. 我需要访问一个全局变量,使其状态保持不同的服务器请求。
In this example the global variable is r
and it is incremented at each request. 在此示例中,全局变量是
r
并且在每个请求时递增。
How can I make r
global in cherrypy? 我怎样才能让
r
全球化?
import cherrypy
import urllib
class Root(object):
@cherrypy.expose
def index(self, **params):
jsondict = [('foo', '1'), ('fo', '2')]
p = urllib.urlencode(jsondict)
if r!=1
r=r+1
raise cherrypy.HTTPRedirect("/index?" + p)
return "hi"
cherrypy.config.update({
'server.socketPort': 8080
})
cherrypy.quickstart(Root())
if __name__ == '__main__':
r=1
To access a global variable, you have to use the global
keyword followed by the name of the variable. 要访问全局变量,必须使用
global
关键字,后跟变量名称。 However, if r
is going to be used only in the Root
class, I recommend you to declare it as a class variable: 但是,如果
r
将仅在Root
类中使用,我建议您将其声明为类变量:
class Root(object):
r = 1
@cherrypy.expose
def index(self, **params):
#...
if Root.r != 1:
Root.r += 1
#...
I had the same problem. 我有同样的问题。 It was solved after realizing my program could access the member variables of an imported library.
它在实现我的程序可以访问导入库的成员变量后得到解决。
First, make a file called myglobals.py and put this in it 首先,创建一个名为myglobals.py的文件并将其放入其中
r=0
visitors = 0
Then in your server: 然后在你的服务器中:
import myglobals
class Root(object):
@cherrypy.expose
def index(self, **params):
#...
if myglobals.r != 1:
myglobals.r += 1
#...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.