我有一个提供文件的应用程序。 HTTP GET / POST / PUT / DELETE方法应该做不同的事情(显然)。因此,我编写了一个对象,表示提供GET / POST / ...方法的文件。此文件由调度程序应用程序的_cp_dispatch
方法返回。请参阅我的源代码。
然而,Cherrypy提出了一个例外说明
TypeError: 'DispatchedFile1' object is not callable
TypeError: unsupported callable
TypeError: <__main__.DispatchedFile1 object at 0x7f209b4e7d30> is not a callable object
如果我使用&#34;正常&#34;使用@expose
d index
方法创建网络应用的方法此示例正常工作。
import cherrypy, os
@cherrypy.expose
class DispatchedFile1(object):
def __init__(self, path):
self._path = path
def GET(self, start = 0, chunk_size = 0):
if(start and chunk_size):
return "{} ; OFFSET: {}, CHUNK_SIZE: {}".format(self._path,
start, chunk_size).encode("UTF-8")
return self._path.encode("UTF-8")
class DispatchedFile2(object):
def __init__(self, path):
self._path = path
@cherrypy.expose
def index(self, start = 0, chunk_size = 0):
if(start and chunk_size):
return "{} ; OFFSET: {}, CHUNK_SIZE: {}".format(self._path,
start, chunk_size).encode("UTF-8")
return self._path.encode("UTF-8")
class FileDispatcherApp1(object):
def _cp_dispatch(self, vpath):
print(vpath)
res = DispatchedFile1("/".join(vpath))
vpath.clear()
print(vpath)
return res
class FileDispatcherApp2(object):
def _cp_dispatch(self, vpath):
print(vpath)
res = DispatchedFile2("/".join(vpath))
vpath.clear()
print(vpath)
return res
class DummyApp(object):
@cherrypy.expose
def index(self):
return "index"
cherrypy.tree.mount(FileDispatcherApp1(), "/files1")
cherrypy.tree.mount(FileDispatcherApp2(), "/files2")
cherrypy.quickstart(DummyApp(), "/")
第二个版本运行正常,但它无法满足我的需求。 我在这里错过了什么吗?我该如何修复我的第一个版本?
PS:我知道我可以使用cherrypy.request
手动查找方法。
答案 0 :(得分:1)
好吧,事实证明我忘了添加正确的请求调度程序。
正确的源代码是:
import cherrypy, os
@cherrypy.expose
class DispatchedFile1(object):
def __init__(self, path):
self._path = path
def GET(self, start = 0, chunk_size = 0):
if(start and chunk_size):
return "{} ; OFFSET: {}, CHUNK_SIZE: {}".format(self._path,
start, chunk_size).encode("UTF-8")
return self._path.encode("UTF-8")
class DispatchedFile2(object):
def __init__(self, path):
self._path = path
@cherrypy.expose
def index(self, start = 0, chunk_size = 0):
if(start and chunk_size):
return "{} ; OFFSET: {}, CHUNK_SIZE: {}".format(self._path,
start, chunk_size).encode("UTF-8")
return self._path.encode("UTF-8")
class FileDispatcherApp1(object):
def _cp_dispatch(self, vpath):
print(vpath)
res = DispatchedFile1("/".join(vpath))
vpath.clear()
print(vpath)
return res
class FileDispatcherApp2(object):
def _cp_dispatch(self, vpath):
print(vpath)
res = DispatchedFile2("/".join(vpath))
vpath.clear()
print(vpath)
return res
class DummyApp(object):
@cherrypy.expose
def index(self):
return "index"
cherrypy.tree.mount(FileDispatcherApp1(), "/files1", {"/": {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}})
cherrypy.tree.mount(FileDispatcherApp2(), "/files2")
cherrypy.quickstart(DummyApp(), "/")
安装应用程序时请注意{'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
。