Question

I had previously learnd that in cherrypy you have to expose a method to make it a view target and this is also spread all over the documentation:

  import cherrypy
  @cherrypy.expose
  def index():
    return "hello world"

But I have inherited a cherrypy application which seems to work without exposing anything

How does this work? Was the exposing requirement removed from newer versions?

It is not easy googling for this, I found a lot about exposing and decorators on cherrypy, but nothing about "cherrypy without expose"

This is the main serve.py script, I removed some parts from it for brevity here:

# -*- coding: utf-8 -*-

import cherrypy
from root import RouteRoot


dispatcher = cherrypy.dispatch.RoutesDispatcher()
dispatcher.explicit = False
dispatcher.connect(u'system',      u'/system', RouteRoot().index)

conf = {
  '/' : {
    u'request.dispatch' : dispatcher,
    u'tools.staticdir.root' : conf_app_BASEDIR_ROOT, 
    u'log.screen' : True,
  },
  u'/my/pub' : {
    u'tools.staticdir.debug' : True,
    u'tools.staticdir.on' : True,
    u'tools.staticdir.dir' : u"pub",
  },
}
#conf = {'/' : {'request.dispatch' : dispatcher}}

cherrypy.tree.mount(None, u"/", config=conf)
import conf.ip_config as ip_config  
cherrypy.config.update({
  'server.socket_host': str(ip_config.host),
  'server.socket_port': int(ip_config.port),
})

cherrypy.quickstart(None, config=conf)

And there is no èxpose` anywhere in the application. How can it work?

File root.py:

# -*- coding: utf-8 -*-

from mako.template import Template

class RouteRoot:

  def index(self):
    return "Hello world!"
Était-ce utile?

La solution

Because it relies on the routes dispatcher which works slightly differently. Mainly, it doesn't need the exposed attribute that the expose decorator sets because the URLs are explicitly described (as you can see with the connect(...) method). On the other hand, the default CherryPy dispatcher doesn't provide an explicit mapping between URLs and objects. When a request hits the application's engine, it must be go through the tree of applications you mounted initially. It uses the exposed attribute to determine if a method can take part in the URL mapping. This gives a chance to the developer to write methods in a controller class that can't be accessed by a URL mapping process.

Autres conseils

I have read this page: http://docs.cherrypy.org/stable/concepts/dispatching.html

I am not sure but maybe the dispatching replaces the necessity for exposing.

It is because the app doesn't uses the default dispatcher. It is explained (in bold!) in cherrypy's doc upon dispatchers

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top