简体   繁体   中英

How do I send an XML ElementTree with Python Requests?

I want to send an XML POST request using the Python 3 Requests library.

When I create my XML body as a plaintext string, I am able to send XML bytes to the server without any issues. However, if I send my request as an ElementTree.Element , the server responds with the error message " Premature end of file ".

Writing XML as plaintext (works)

import requests

root = """<?xml version = '1.0'?>
          <Kronos_WFC version = '1.0'> </Kronos_WFC>"""
headers = {'Content-Type': 'text/xml'}
print(requests.post('http://localhost/wfc/XmlService', data=root, headers=headers)).text

# Output:
# <Kronos_WFC version="1.0" WFCVersion="6.3.13.362" TimeStamp="10/30/2017 12:19PM GMT-04:00"></Kronos_WFC>

Building XML with ElementTree (fails)

from xml.etree import ElementTree as ET
import requests

root = ET.Element("Kronos_WFC", version="1.0")
headers = {'Content-Type': 'text/xml'}
print(requests.post('http://localhost/wfc/XmlService', data=root, headers=headers)).text

# Output:
# <Kronos_WFC>
#    <Response Status="Failure" ErrorCode="-1" Message="Premature end of file.">
#    </Response></Kronos_WFC>

When I tried printing my XML ElementTree to debug, I found that Python was interpreting it as an object, rather than as parsable text. I suspect that this may be the cause of the issue.

root = ET.Element("Kronos_WFC", version="1.0")
print(root)

# Output:
# <Element 'Kronos_WFC' at 0x013492D0>

Ideally I would like to build my XML POST request using ElementTree.Element , then send it to an API using Requests.

How can I send an XML ElementTree.Element to a server using Python Requests?

Use ElementTree.tostring() to create a string representation of the xml.

requests.post(
    'http://localhost/wfc/XmlService', 
    data=ET.tostring(root), 
    headers=headers
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM