Skip to main content
 首页 » 编程设计

python之Cherrypy REST 教程返回 TypeError : _expose() takes exactly 1 argument

2025年01月19日13over140

尝试按照 cherrypy 文档页面上的教程 7 创建 REST 样式 API。从 tutorial 复制粘贴代码,

import random 
import string 
 
import cherrypy 
 
@cherrypy.expose 
class StringGeneratorWebService(object): 
 
    @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 
 
    def PUT(self, another_string): 
        cherrypy.session['mystring'] = another_string 
 
    def DELETE(self): 
        cherrypy.session.pop('mystring', None) 
 
 
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(StringGeneratorWebService(), '/', conf) 

但是运行时报错

File "H:/researchInstrumentCatalog/dqapi/core/test.py", line 36, in <module> 
cherrypy.quickstart(test(), '/', conf) 
TypeError: expose_() takes exactly 1 argument (0 given)  

我正在运行 cherrypy 3.8,因此 this question没有帮助

请您参考如下方法:

在您链接的问题中,我提到在 CherryPy 版本 6 中添加了使用 cherrypy.expose 装饰类的支持。

您使用的是 3.8。

将 CherryPy 升级到 6.0 之后的任何版本,或者只是不使用 expose 装饰并设置 exposed = True 的属性。

class StringGeneratorWebService(object): 
 
    # this is the attribute that configured the expose decorator 
    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 
 
    def PUT(self, another_string): 
        cherrypy.session['mystring'] = another_string 
 
    def DELETE(self): 
        cherrypy.session.pop('mystring', None)