Search code examples
pythonjsoncherrypy

'Request' object has no attribute 'json'


I've run the following command in the terminal to verify my current installation of cherryPy

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

However, the following code results in error:

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

When running this I get the following error:

  File "C:\Anaconda\lib\site-packages\cherrypy\__init__.py", line 224, in __getattr__
    return getattr(child, name)

AttributeError: 'Request' object has no attribute 'json'

EDIT:

This is how I'm sending the request:

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

Edit 2: I'm doing this all in Eclipse with PyDev. If I control-click on request in cherrypy.request it opens up the file cherypy__init__.py as should be expected. However, if I control-click on json, it doesn't know where the file is.

I've tried uninstalling the library manually - and then redownloading from https://pypi.python.org/pypi/CherryPy/3.2.4 and placing the appropriate folders in C:\Anaconda\Lib\site-packages


Solution

  • Are you posting the json object? This code works fine for me.

    import cherrypy
    
    class HelloWorld(object):
        @cherrypy.expose
        @cherrypy.tools.json_in() 
        def observe(self, urlParam1=None):
            print(cherrypy.request.json)
            return ""
    
        @cherrypy.expose
        def asdf(self):
            return """<!DOCTYPE HTML>
                      <html>
                      <head>
                      <script>function Sendjson(){
                      // code for IE7+, Firefox, Chrome, Opera, Safari
                      if(window.XMLHttpRequest)
                          xmlhttp=new XMLHttpRequest();
                      else// code for IE5
                          xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
    
                      xmlhttp.open("POST","/observe", true);
                      xmlhttp.setRequestHeader('Content-Type', 'application/json');
                      xmlhttp.send(JSON.stringify(({name:"Bob"})));
                      }
                      </script>
                      </head>
                      <body onload="Sendjson();">
                      </body>
                      </html>"""
    
    cherrypy.quickstart(HelloWorld())
    

    Hope this helps!