Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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
like image 753
Mirko Cianfarani Avatar asked Apr 07 '13 02:04

Mirko Cianfarani


1 Answers

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
        #...
like image 200
A. Rodas Avatar answered Oct 18 '22 07:10

A. Rodas