无法在cherryPy中一起添加多个应用程序 [英] Unable to add more than one applications together in cherryPy
问题描述
当我这样做并尝试访问"/api"时,cherryPy会抛出"TypeError:'ApiStringGenerator'对象不可调用"错误
When I do this and try to access "/api" than cherryPy throws "TypeError: 'ApiStringGenerator' object is not callable" error
'''
Created on Jan 11, 2016
@author: ankurjat
'''
import cherrypy
import random
import string
import os
conf = {'/': {'tools.sessions.on': True,
'tools.staticdir.root': os.path.abspath(os.getcwd())},
'/static': {'tools.staticdir.on': True,
'tools.staticdir.dir': './resources'},
'/api': {'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.sessions.on': True,
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'text/plain')]}
}
class ApiStringGenerator(object):
exposed = True
@cherrypy.tools.accept(media='text/plain')
def GET(self, length=8):
value = cherrypy.session['mystring']
return value
def POST(self, length=8):
value = ''.join(random.sample(string.hexdigits, int(length)))
cherrypy.session['mystring'] = value
return value
def PUT(self, value):
cherrypy.session['mystring'] = value
def DELETE(self):
cherrypy.session.pop('mystring', None)
class StringGenerator(object):
@cherrypy.expose
def index(self):
return file('templates/index.html')
if __name__ == '__main__':
cherrypy.tree.mount(ApiStringGenerator(), '/api', conf)
cherrypy.tree.mount(StringGenerator(), '/', conf)
cherrypy.engine.start()
cherrypy.engine.block()
但是当我更改下面的行
cherrypy.tree.mount(ApiStringGenerator(), '/api', conf)
cherrypy.tree.mount(StringGenerator(), '/', conf)
cherrypy.engine.start()
cherrypy.engine.block()
通过代码
webapp = StringGenerator()
webapp.api = ApiStringGenerator()
cherrypy.quickstart(webapp, '/', conf)
然后没有错误,一切正常.请帮忙.
Then no error and everything works fine. Please help.
推荐答案
问题是cherrypy中的配置是相对于安装点的.
The problem is that the configuration in cherrypy is relative to the mountpoint.
因此,当您在安装点/api
中的/api
中配置 MethodDispatcher
时.您正在激活/api/api
中的 MethodDispatcher
,并且在/api
中使用的调度程序是默认调度程序,因此尝试调用对象,因为该对象具有 exposed
属性,但不能调用.这是默认调度程序的行为.
So when you are configuring the MethodDispatcher
in /api
inside the mount point /api
. You are activating the MethodDispatcher
inside /api/api
and the dispatcher that's gets used in /api
it's the default one, hence trying to call the object because the object has the exposed
attribute but it's not callable. Which is the behavior of the default dispatcher.
如果您想这样做:
cherrypy.tree.mount(ApiStringGenerator(), '/api', conf)
该配置必须相对于/api
:
{'/': {'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.sessions.on': True,
'tools.response_headers.on': True,
'tools.response_headers.headers': [('Content-Type', 'text/plain')]}}
这篇关于无法在cherryPy中一起添加多个应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!