Frage

I'm trying to send a request to an API that only accepts XML. I've used elementtree.SimpleXMLWriter to build the XML tree and it's stored in a StringIO object. That's all fine and dandy.

The problem is that I have to urlencode the StringIO object in order to send it to the API. But when I try, I get:

  File "C:\Python27\lib\urllib.py", line 1279, in urlencode
    if len(query) and not isinstance(query[0], tuple):
AttributeError: StringIO instance has no attribute '__len__'

Apparently this has been discussed as an issue with Python. I'm just wondering if there are any other built-in functions for urlencoding a string, specifically ones that don't need to call len() so that I can encode this StringIO object.

Thanks!

PS: I'm open to using something other than StringIO for storing the XML object, if that's an easier solution. I just need some sort of "file" for SimpleXMLWriter to store the XML in.

War es hilfreich?

Lösung

StringIO instance is like a file, not like a string. It does not have a len(). Use my_string_io_varaible.getvalue() to get the string value, and pass it to urlencode() which expects a string.

Maybe you could urlencode URLs that you embed into the XML along the way, instead of the whole thing.

Andere Tipps

You can get a string from your StringIO by calling its getvalue() method, and pass that to urllib.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top