在_cp_dispatch中调用类方法不起作用?

时间:2017-11-30 15:26:50

标签: python http cherrypy

我试图在_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。否则,当我输入网址8080:/ ABC时,我收到404错误,说path to /ABC/ not found 这是什么问题?

是否无法使用cherrypy为单个URL路径创建多个方法?

1 个答案:

答案 0 :(得分:0)

搞定了!

刚刚创建了第二个类来保存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)