views:

44

answers:

1

Hi,

I've been looking around the CherryPy documentation, but can't quite get my head around what I want to do. I suspect it might be more of a Python thing than a CherryPy thing...

My current class looks something like this:

import managerUtils

class WebManager:
    def A(self, **kwds):
        return managerUtils.runAction("A", kwds)
    A.enabled = True

    def B(self, **kwds):
        return managerUtils.runAction("B", kwds)
    B.enabled = True

    def C(self, **kwds):
        return managerUtils.runAction("C", kwds)
    C.enabled = True

Obviously there's a lot of repetition in here.

in managerUtils.py, I have a dict that's something like:

actions = {'A': functionToRunForA,
           'B': functionToRunForB,
           'C': functionToRunForC}

Okay, so that's a slightly simplistic view of it, but I'm sure you get the idea.

I want to be able to do something like:

import managerUtils

class WebManager:
    def __init__(self):
        for action in managerUtils.actions:
            f = registerFunction(action)
            f.enabled = True

Any ideas of how to do this?

One answer suggested doing:

class WebManager:
    def index(self, action, **kwds):
        return managerUtils.runAction(action, kwds)
    index.enabled = True

That picks up, I believe:

http://webserver/?action&kwds

Rather than what I want, which is:

http://webserver/action?kwds

When I do what you suggest, I get the following 404 error:

Traceback (most recent call last):
  File "/Library/Python/2.5/site-packages/cherrypy/_cprequest.py", line 606, in respond
    cherrypy.response.body = self.handler()
  File "/Library/Python/2.5/site-packages/cherrypy/_cperror.py", line 227, in __call__
    raise self
NotFound: (404, "The path '/myAction' was not found.")
+2  A: 
class WebManager:
    def default(self, action, **kwds):
        return managerUtils.runAction(action, kwds)
    default.exposed = True

Two notes about why this is different than other answers:

  1. .exposed is the correct attribute for publishing methods, not .enabled
  2. the index method is the only one which does not allow positional arguments like "action". Use a default method instead.

Hope that helps!

fumanchu
Let me give that one a go!The exposed/enabled thing was a typo on my part - my initial setup (the top block of my question) was using "exposed" - I just mis-typed when writing it in that generic way.Will give "default" a go now - thanks!
Hugh
Works wonderfully - thanks for the help!
Hugh