3
votes

I'm getting:

<error>You have an error in your XML syntax...

when I run this python script I just wrote (I'm a newbie)

import requests

xml = """xxx.xml"""

headers = {'Content-Type':'text/xml'}

r = requests.post('https://example.com/serverxml.asp', data=xml)

print (r.content);

Here is the content of the xxx.xml

<xml>
<API>4.0</API>
<action>login</action>
<password>xxxx</password>
<license_number>xxxxx</license_number>
<username>xxx@xyz.com</username>
<training>1</training>
</xml>

I know that the xml is valid because I use the same xml for a perl script and the contents are being printed back.

Any help will greatly appreciated as I am very new to python.

1
You are not actually reading in the file. AFAIK the parameter data expects the actual contents of your XML file, not its nameUnholySheep
Found the documentation data -- (optional) Dictionary, bytes, or file-like object to send in the body of the Request. So you need to either parse the XML file into something you can attach or open the file and pass that object to the parameterUnholySheep

1 Answers

9
votes

You want to give the XML data from a file to requests.post. But, this function will not open a file for you. It expects you to pass a file object to it, not a file name. You need to open the file before you call requests.post.

Try this:

import requests

# Set the name of the XML file.
xml_file = "xxx.xml"

headers = {'Content-Type':'text/xml'}

# Open the XML file.
with open(xml_file) as xml:
    # Give the object representing the XML file to requests.post.
    r = requests.post('https://example.com/serverxml.asp', data=xml)

print (r.content);