开发者

CodeIgniter-like Routes in CherryPy

I'm coming from PHP frameworks, and one thing I like about them is that routing is sort of taken care of for me: I can drop all of my controllers in the directory controllers and it will automatically call Posts::delete(12) when a user visits http://www.example.com/posts/delete/12. I realize that I can use Routes with CherryPy, but I'm kind of annoyed with how limited the documentation is— there's nothing on how I should format my class name (should I call it PostsController()? does i开发者_Go百科t even care?), using routes.mapper.connect() vs routes.connect(), and what happens when it calls the default route (/:controller/:action/:id).

I'd really like to use Python, but I don't want to have to define every single route. Could someone point me to a Python web-framework newb tutorial on how to use Routes or just explain how one goes about structuring a CherryPy web-app so that I can have a couple of Routes laid out like

d = cherrypy.dispatch.RoutesDispatcher()
d.mapper.connect('main', '/:controller/:action', controller='root', action='index')
d.mapper.connect('main', '/:controller/:action/:id', controller='root', action='index')

and it will handle it for me? Thanks.


Simple way is to use cherrypy.tree.mount to mount a controller object. The structure of the controller will give you your basic routes.

For example:

import cherrypy

class AppRoot:
    def index(self):
        return "App root's index"
    index.exposed = True

    controller1 = Controller1Class()
    # controller2 = Controller2Class(), etc.

class Controller1Class:

     def index(self):
         return "Controller 1's index"
     index.exposed = True

     def action1(self, id):
         return "You passed %s to controller1's action1" % id      
     action1.exposed = True

     # def action2(self, id): etc...

# ... the rest of the config stuff ...

cherrypy.tree.mount(AppRoot(), '/')  

# ... the rest of the startup stuff....

Calling the following URIs will call the following methods:

  • http://mysite.com/index -> AppRoot::index()
  • http://mysite.com/controller1 -> Controller1Class::index()
  • http://mysite.com/controller1/action1 -> Controller1Class::action1()
  • http://mysite.com/controller1/action1/40 -> Controller1Class::action1("40")

See also:

  • http://mark.biek.org/blog/2009/07/basic-routing-with-cherrypy/
  • http://www.cherrypy.org/wiki/PageHandlers
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜