문제

I'm using method dispatcher in CherryPy. In the server/start.py part of the server, I need to instantiate the API classes.

To make it more modular, and not to put everything in the start.py file, I coded it like this.

So, I've a dict which has all the instantiated api classes.

services = {}
user = UserResource() #api class
foo = FooResource() #api class
services = {"user":user, "foo":foo}

class Server(object):
    """Initialise the Cherrypy app"""
    #for service in services:
    user = services.values()[0]


cherrypy.quickstart(Server())

That works. But, if I do services.keys()[0] = services.values()[0] it doesn't work at all. No routes.

How do I do such a thing? Where I don't have to assign it to a particular class inside the server class, but rather use the keys to add routes.

도움이 되었습니까?

해결책

services.keys() simply returns a list. Setting the first element of that list to anything will have no effect.

I expect you want to do services[services.keys()[0]] = services.values()[0], although I can't imagine what you are trying to do with that code.

Edit

OK, I think I understand what you want to do. It seems that CherryPy relies on class-level attributes to define the routes it will serve. The docs show how to do this dynamically. In your case, you could do something like this:

class Server(object):
    pass

for k, v in services:
    setattr(Server, k, v)

Note that the setattr has to be done outside the class definition itself, as the Server name doesn't exist inside the class body.

다른 팁

If you want to have more routing flexibility, use RoutesDispatcher.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top