开发者

Dynamically creating page definitions in Cherrypy

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:

开发者_如何学Chttp://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.")


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜