【问题标题】:Calling class method within _cp_dispatch doesn't work?在 _cp_dispatch 中调用类方法不起作用?
【发布时间】:2017-11-30 15:26:50
【问题描述】:

我试图在 _cp_dispatch 方法中调用一个cherrypy暴露的类方法,例如:

class ABC(object):

@cherrypy.expose
def post(self):
    return "POSTING"

def _cp_dispatch(self, vpath):
    if len(vpath) == 1:
        return self.post()
    return vpath

但是“post”方法不会被调用,除非我将它更改为 index(self),并告诉 _cp_dispatch 返回 self。否则,当我输入一个 url 8080:/ABC 时,我会收到一个 404 错误说 path to /ABC/ not found 这里有什么问题?

难道不能使用cherrypy为单个URL路径创建多个方法吗?

【问题讨论】:

    标签: python http cherrypy


    【解决方案1】:

    搞定了!

    刚刚创建了第二个类来保存 get 和 post 方法。完整代码如下所示:

    import cherrypy
    import random
    import string
    
    class data(object):
    def __init__(self):
        self.catalogue = catalogue()
    
    def _cp_dispatch(self, vpath):
        if len(vpath) == 1:
            return self.catalogue
    
        return vpath
    
    class catalogue(object):
    exposed = True
    
    @cherrypy.tools.accept(media='text/plain')
    def GET(self):
        return cherrypy.session['mystring']
    
    def POST(self, length=8):
        some_string = ''.join(random.sample(string.hexdigits, int(length)))
        cherrypy.session['mystring'] = some_string
        return some_string
    
    if __name__ == '__main__':
    conf = {
        '/': {
            'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
            'tools.sessions.on': True,
            'tools.response_headers.on': True,
            'tools.response_headers.headers': [('Content-Type', 'text/plain')]
        }
    }
    cherrypy.quickstart(data(),'/',conf)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 1970-01-01
      • 2016-05-23
      • 2018-03-02
      • 1970-01-01
      相关资源
      最近更新 更多