Reading POST body with bottle.py

Martín Coll picture Martín Coll · Feb 20, 2013 · Viewed 33.2k times · Source

I am having trouble reading a POST request with bottle.py.

The request sent has some text in its body. You can see how it's made here on line 29: https://github.com/kinetica/tries-on.js/blob/master/lib/game.js.

You can also see how it's read on a node-based client here on line 4: https://github.com/kinetica/tries-on.js/blob/master/masterClient.js.

However, I haven't been able to mimic this behavior on my bottle.py-based client. The docs say that I can read the raw body with a file-like object, but I can't get the data neither using a for loop on request.body, nor using request.body's readlines method.

I'm handling the request in a function decorated with @route('/', method='POST'), and requests arrive correctly.

Thanks in advance.


EDIT:

The complete script is:

from bottle import route, run, request

@route('/', method='POST')
def index():
    for l in request.body:
        print l
    print request.body.readlines()

run(host='localhost', port=8080, debug=True)

Answer

Jan Vlcinsky picture Jan Vlcinsky · Apr 20, 2014

Did you try simple postdata = request.body.read() ?

Following example shows reading posted data in raw format using request.body.read()

It also prints to the log file (not to the client) raw content of body.

To show accessing of form properties, I added returning "name" and "surname" to the client.

For testing, I used curl client from command line:

$ curl -X POST -F name=jan -F surname=vlcinsky http://localhost:8080

The code which works for me:

from bottle import run, request, post

@post('/')
def index():
    postdata = request.body.read()
    print postdata #this goes to log file only, not to client
    name = request.forms.get("name")
    surname = request.forms.get("surname")
    return "Hi {name} {surname}".format(name=name, surname=surname)

run(host='localhost', port=8080, debug=True)