【问题标题】:Unable to add more than one applications together in cherryPy无法在cherryPy中添加多个应用程序
【发布时间】:2016-04-17 14:00:27
【问题描述】:

当我这样做并尝试访问“/api”时,cherryPy 会抛出“TypeError: 'ApiStringGenerator' object is not callable”错误

'''
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)

然后没有错误,一切正常。 请帮忙。

【问题讨论】:

    标签: python typeerror cherrypy


    【解决方案1】:

    问题是cherrypy中的配置是相对于挂载点的。

    因此,当您在挂载点/api 内配置/api 中的MethodDispatcher 时。您正在激活/api/api 内的MethodDispatcher,而/api 中使用的调度程序是默认调度程序,因此尝试调用该对象,因为该对象具有exposed 属性但它不可调用。这是默认调度程序的行为。

    如果你想做:

    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')]}}
    

    【讨论】:

    • 谢谢@Cyraxjoe。有效。现在我创建了两个 conf 字典,一个用于 '/',另一个用于 '/api',在他们的 conf 字典中我将它们安装在 '/' 上并且它起作用了。 :)
    猜你喜欢
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2012-01-11
    相关资源
    最近更新 更多