سؤال

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

هل كانت مفيدة؟

المحلول 2

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!

نصائح أخرى

The JSON parameter does not exist in the OPTION method, only in the POST. With CORS, when you POST, you have 2 requests: one is a OPTION, the second is the POST.

Add a simple test in your method:

 @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

You might run into this issue if you are missing json_in()

@cherrypy.tools.json_in()
def POST(self, ...):
     ...

Well, it's true, you are sending the POST data as JSON, not as typical form-encoded data, and thus you never set the key json. You can do

$.ajax({
    type : "POST",
    url : 'http://10.XX.X.XXX:XXXX/observe',
    data : {json: insertJSON},
    //      ^^^^
    success : function(result) {
        alert('observation inserted');
    }
});

Or if you really want to send the data JSON encoded, you have to access the raw request body. See How to receive JSON in a POST request in CherryPy?.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top