Extract data from "request.json"

334 views
Skip to first unread message

Gourinda Adil

unread,
Sep 23, 2018, 7:32:06 PM9/23/18
to bottlepy
Please I need help, how to extract data from "request.json", does the syntax is:
   -request.json["key"]
      or
   -request.json.get("key") (as a FormsDic)
Please I am very confused and I am very as my first example with bottle didn't work :-(

gNeandr

unread,
Sep 24, 2018, 3:41:21 AM9/24/18
to bott...@googlegroups.com

Not sure this little example is what you look for:

   with open(xP.prefsJSONfile) as data_file:
       xP.prefs = json.load(data_file)
   xP.prefs['keyname'] = somedata

--
--
You are member of the "bottlepy" group at google groups.
See http://groups.google.de/group/bottlepy for mailing list options.
See http://bottlepy.org/ for news and documentation.

---
You received this message because you are subscribed to the Google Groups "bottlepy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to bottlepy+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Marcel Hellkamp

unread,
Sep 24, 2018, 6:12:16 AM9/24/18
to bott...@googlegroups.com
Why not just test it yourself? What did not work? What is the expected
result, and what did you see instead?

request.json returns a dict, but only of the request actually contained
json data and had the correct content-type header set.

http://bottlepy.org/docs/0.12/api.html#bottle.BaseRequest.json

Gourinda Adil

unread,
Sep 26, 2018, 11:38:49 AM9/26/18
to bottlepy
I have a little idea and I want to test is with Bottle:
I want to take the text of a <h1> tag, adding some text and putt it in <p> tag, and I want to do it with XMLHttpRequest() object:

--- template.tpl ---

<!DOCTYPE html>
<html>
  
   <head>
      <title>bottle example</title>
     
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script type="text/javascript">
         $(document).ready(//---begin---
                           function(){//---begin---
                                      $("p").on(//---begin---
                                                "click"
                                                ,function(){//---begin---
                                                            var my_request = new XMLHttpRequest();
                                                            my_request.open("POST" ,url:"/hello");
                                                            var request_data = {"h1_value":$("h1").text()};
                                                            my_request.setRequestHeader("Content-Type" ,"application/json");
                                                            my_request.send(request_data);

                                                            $('p').text(my_request.responseText);
                                                           }//---end---
                                               )//---end---
                                         
                                     }//---end---
                          )//---end---
      </script>
   </head>
  
   <body>
       <h1>Hello World</h1>
    <p></p>
   </body>

</html>
-------------------------------------

--- Bottle.py ------------------

from bottle import route ,run ,template ,request

#----- URL:/hello -----
   #----- Template -----
@route("/hello")
def example():
    return template("template.tpl")
   #----- POST+GET -----
@route("/hello", method=['POST' ,'GET'])
def ajax():
    json_data = request.json["h1_value"] + "and Welcome to Bottle"
    return {"returned_json":json_data}

run(host='127.0.0.1', port=8080, debug=True)
----------------------------------------

But I get this error:
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/bottle.py", line 862, in _handle
    return route.call(**args)
  File "/usr/lib/python3/dist-packages/bottle.py", line 1740, in wrapper
    rv = callback(*a, **ka)
  File "Bottle.py", line 17, in ajax
    json_data = request.json["h1_value"] + "and Welcome to Bottle"
TypeError: 'NoneType' object is not subscriptable

Please if you can help me Because I wasn't able to resolve this problem since 1 week and it begin to make me crasy.

Thanks for your help

peb aryan

unread,
Sep 26, 2018, 11:58:59 AM9/26/18
to bott...@googlegroups.com
request_data content is still a javascript Object, you need to pass a JSON string to send() function using i.e. JSON.stringify()

my_request.send(JSON.stringify(request_data));  

--

Marcel Hellkamp

unread,
Sep 26, 2018, 12:14:50 PM9/26/18
to bott...@googlegroups.com
You are not sending JSON to the server. Passing an object to
`HttpRequest.send()` is undefined behavior.  In your client-side code,
`my_request.send(request_data);` should be
`my_request.send(JSON.stringify(request_data));`.

If you are struggling with this for a whole week, you should probably
find better ways to debug your application. Print or log whats in
`request.json` or, if that is None, inspect the raw request body
(`request.body`) or the headers sent by the client. Use the developer
tools of your browser to check if your client-side code does what you
think it does. Test your application with curl, wget or the python
requests library, or any other HTTP tool other than your browser, and
verify if it behaves correctly.

Also, bottle is a micro-framework for a reason. The `request.json`
method is just 11 lines of code [1] without comments. You can find out
why the return value might be `None` quite easily.

[1] http://bottlepy.org/docs/dev/_modules/bottle.html#BaseRequest.json

Good luck,
Marcel
Reply all
Reply to author
Forward
0 new messages