How do I use a global variable in cherrypy?
Asked Answered
A

2

5

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.

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
Addend answered 7/4, 2013 at 2:4 Comment(2)
What exactly is your question?Putman
I update the question and with this variable global r. I have the errorAddend
G
7

To access a global variable, you have to use the global keyword followed by the name of the variable. However, if r is going to be used only in the Root class, I recommend you to declare it as a class variable:

class Root(object):
    r = 1
    @cherrypy.expose
    def index(self,  **params):
        #...
        if Root.r != 1:
            Root.r += 1
        #...
Greenbrier answered 7/4, 2013 at 3:22 Comment(0)
U
3

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

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
            #...
Umbrageous answered 18/1, 2014 at 0:9 Comment(1)
it doesnot work if I use a redis queue to call a method ,i.e., if I have a method which basically enqueues a method in different file, modified value of the variable is not accessible unless the specifically pass value to the method. Also, my variable has to modified while initiating the cherrypy serverDip

© 2022 - 2024 — McMap. All rights reserved.