0

How would you suggest I post xml data to a url in django.

For example, in my views.py when the view is called, I am trying to do a post to a url and then return the xml response content.

What I have so far:

import xml
URL ="http://something.com"

def process(request):
    response = None
    if request.method=="POST":
        xml_data = """
            <?xml version='1.0' encoding='UTF-8'?>
            <something><retrieve_user>Tammy</retrieve_user></something>
        """
        headers = {
            "Host": "myhost",
            "Content-Type": "text/xml; charset=UTF-8",
            "Content-Length": len(xml_data)
        }

        #make response variable equal to process to post xml_data and headers to URL
        response = ??

    return response

After this, how can I get the value of the response content. For example if the response content returned this:

<response_begin> 
    <array>
        <info>
            <name>Name Something</name>
            <email>Email Something</email>
        </info>
        <info>...</info>
    </array>
</response_begin>

How can I retrieve the values "Name Something" and "Email Something"? Thanks in advance.

user875139
  • 1,599
  • 4
  • 23
  • 44
  • 1
    Possible duplicate of [How do I parse XML in Python?](http://stackoverflow.com/questions/1912434/how-do-i-parse-xml-in-python) – rnevius Feb 24 '16 at 17:39

2 Answers2

1

I think the django portion is a red-herring in this case. Check out the python build-in httplib module. It will allow you to make a POST request. There are examples at the bottom of the page.

https://docs.python.org/2/library/httplib.html

You'll want to change the Content-type and Accepts headers to "text/xml" or "application/xml".

TehCorwiz
  • 365
  • 2
  • 9
1

I found an article that helped me solve the posting problem beautiful using httplib.

https://gist.github.com/hoest/3655337

import httplib
import xml.dom.minidom

HOST = "www.domain.nl"
API_URL = "/api/url"

def do_request(xml_location):
    """HTTP XML Post request"""
    request = open(xml_location, "r").read()

webservice = httplib.HTTP(HOST)
webservice.putrequest("POST", API_URL)
webservice.putheader("Host", HOST)
webservice.putheader("User-Agent", "Python post")
webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
webservice.putheader("Content-length", "%d" % len(request))
webservice.endheaders()

webservice.send(request)

statuscode, statusmessage, header = webservice.getreply()

result = webservice.getfile().read()
resultxml = xml.dom.minidom.parseString(result)

print statuscode, statusmessage, header
print resultxml.toprettyxml()
user875139
  • 1,599
  • 4
  • 23
  • 44