How to use global variable in cherrypy?

I need to access a global variable that maintains its state compared to other servers.

In this example, the global variable r , and it increases with each request.

How can I make r global in cherrypy?

 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 
+4
source share
2 answers

To access a global variable, you must use the global , followed by the variable name. However, if r will be used only in the Root class, I recommend that you declare it as a class variable:

 class Root(object): r = 1 @cherrypy.expose def index(self, **params): #... if Root.r != 1: Root.r += 1 #... 
+5
source

I had the same problem. It was resolved after my program could access the member variables of the imported library.

First create a file called myglobals.py and put it in it

 r=0 visitors = 0 

Then on your server:

 import myglobals class Root(object): @cherrypy.expose def index(self, **params): #... if myglobals.r != 1: myglobals.r += 1 #... 
+2
source

All Articles