Search code examples
pythonapiresthttplib

Python: issue in displaying as a list httplib.HTTPMessage


I have a small problem here. So, I am writing some calls for a well known REST API. Everything is going well, except the fact that I want all the response to be displayed as a list(which is better for me to manipulate). My function is this:

import sys, httplib

HOST =  "api.sugarsync.com"
API_URL = "https://api.sugarsync.com"

def do_request(xml_location):
       request = open(xml_location,"r").read()
       webservice = httplib.HTTPS(HOST)
       webservice.putrequest("POST", "authorization", API_URL)
       webservice.putheader("Host", HOST)
       webservice.putheader("User-Agent","Python post")
       webservice.putheader("Content-type", "application/xml")
       webservice.putheader("Content-type", "application/xml")
       webservice.putheader("Accept", "*/*")
       webservice.putheader("Content-length", "%d" % len(request))
       webservice.endheaders()
       webservice.send(request)
       statuscode, statusmessage, header = webservice.getreply()
       result = webservice.getfile().read()
       return statuscode, statusmessage, header
       return result

do_request('C://Users/my_user/Documents/auth.xml')

I am used to use split() but in this case the result is this:

[201, 'Created', <httplib.HTTPMessage instance at 0x0000000001F68AC8>]

Well, I need also the third object(httplib.HTTPMessage instance at 0x0000000001F68AC8>), to be displayed as list, to extract some of the data in there.

Thanks in advance!


Solution

  • httplib.HTTPMessage is something like dict, here is a sample:

    import httplib
    from cStringIO import StringIO
    
    h = httplib.HTTPMessage(StringIO(""))
    h["Content-Type"] = "text/plain"
    h["Content-Length"] = "1234"
    
    print h.items()
    

    you just call it's function items(), it will return a list of headers