POST flask server with XML from python

10,951

First, i would add -H "Content-Type: text/xml" to the headers in the cURL call so the server knows what to expect. It would be helpful if you posted the server code (not necessarily everything, but at least what's failing).

To debug this i would use

@app.before_request
def before_request():
    if True:
        print "HEADERS", request.headers
        print "REQ_path", request.path
        print "ARGS",request.args
        print "DATA",request.data
        print "FORM",request.form

It's a bit rough, but helps to see what's going on at each request. Turn it on and off using the if statement as needed while debugging.

Running your request without the xml header in the cURL call sends the data to the request.form dictionary. Adding the xml header definition results in the data appearing in request.data. Without knowing where your server fails, the above should give you at least a hint on how to proceed.

EDIT referring to comment below:

I would use the excellent xmltodict library. Use this to test:

import xmltodict
@app.before_request
def before_request():
    print xmltodict.parse(request.data)['xml']['From']

with this cURL call:

curl -X POST -d '<xml><From>Jack</From><Body>Hello, it worked!</Body></xml>' localhost:5000 -H "Content-Type: text/xml"

'Jack' prints out without issues.

Note that this call has been modified from your question- the 'xml' tag has been added since XML requires a root node (it's called an xml tree for a reason..). Without this tag you'll get a parsing error from xmltodict (or any other parser you choose).

Share:
10,951
JMzance
Author by

JMzance

Updated on June 22, 2022

Comments

  • JMzance
    JMzance almost 2 years

    I have a flask server up and running on pythonanywhere and I am trying to write a python script which I can run locally which will trigger a particular response - lets say the server time, for the sake of this discussion. There is tonnes and tonnes of documentation on how to write the Flask server side of this process, but non/very little on how to write something which can trigger the Flask app to run. I have tried sending XML in the form of a simple curl command e.g.

    curl -X POST -d '<From>Jack</From><Body>Hello, it worked!</Body>' URL
    

    But this doesnt seem to work (errors about referral headers).

    Could someone let me know the correct way to compose some XML which can be sent to a listening flask server.

    Thanks,

    Jack

  • JMzance
    JMzance about 9 years
    Ok so when I add the content type and that before_request call I get back: REQ_path /Testing ARGS ImmutableMultiDict([]) DATA <name>Jack</name> FORM ImmutableMultiDict([]) So then I suppose my question now is, how do I get a 'name' from within Flask (I've tried request.data and request.DATA.name etc.) and as a follow up how would I pass ARGS in the XML (e.g. if I wanted my service to require a user name and password) Cheers @GC_Python