Skip to main content
 首页 » 编程设计

python之“请求”对象没有属性 'json'

2025年05月04日12lori

我在终端中运行了以下命令来验证我当前安装的 cherryPy

python -c "import cherrypy;print cherrypy.__version__" 
3.3.0 

但是,下面的代码会导致错误:

@cherrypy.expose 
@cherrypy.tools.json_in()  
def observe(self, urlParam1=None): 
    print cherrypy.request.json 
    return "" 

运行时出现以下错误:

  File "C:\Anaconda\lib\site-packages\cherrypy\__init__.py", line 224, in __getattr__ 
    return getattr(child, name) 
 
AttributeError: 'Request' object has no attribute 'json' 

编辑:

这就是我发送请求的方式:

 var insertJSON = JSON.stringify(insertObj); 
 
$.ajax({ 
                type : "POST", 
                contentType : "application/json", 
                url : 'http://10.XX.X.XXX:XXXX/observe', 
                data : insertJSON, 
                dataType : "json", 
                success : function(result) { 
                    alert('observation inserted'); 
                } 
            }); 

编辑 2: 我正在使用 PyDev 在 Eclipse 中完成这一切。如果我控制单击 cherrypy.request 中的请求,它会按预期打开文件 cherypy__init__.py。但是,如果我按住 control 并单击 json,它就不知道文件在哪里。

我试过手动卸载库 - 然后从 https://pypi.python.org/pypi/CherryPy/3.2.4 重新下载并将适当的文件夹放在 C:\Anaconda\Lib\site-packages

请您参考如下方法:

OPTION方法中不存在JSON参数,只存在于POST中。 使用 CORS,当您 POST 时,您有 2 个请求:一个是 OPTION,第二个是 POST。

在你的方法中添加一个简单的测试:

 @cherrypy.expose 
 @cherrypy.tools.json_out() 
 @cherrypy.tools.json_in() 
 def dosomething(self): 
     result = {"operation": "request", "result": "success"} 
     if cherrypy.request.method == "POST": 
         print(cherrypy.request.json) 
     return result