用于编码 URL 的 urllib.urlencode 的替代方案
我正在尝试向仅接受 XML 的 API 发送请求。我使用 elementtree.SimpleXMLWriter
构建 XML 树,并将其存储在 StringIO 对象中。一切都很好。
问题是我必须对 StringIO 对象进行 urlencode 才能将其发送到 API。但是当我尝试时,我得到:
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__'
显然这已经被讨论为Python 的问题。我只是想知道是否有任何其他内置函数用于对字符串进行 urlen 编码,特别是那些不需要调用 len() 以便我可以对此 StringIO 对象进行编码的函数。
谢谢!
PS: 我愿意使用 StringIO 以外的其他方式来存储 XML 对象,如果这是一个更简单的解决方案的话。我只需要某种“文件”供 SimpleXMLWriter
将 XML 存储在.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
StringIO
实例就像一个文件,而不是一个字符串。它没有len()
。使用 my_string_io_varaible.getvalue() 获取字符串值,并将其传递给需要字符串的 urlencode() 。也许您可以将 URL 进行
urlencode
嵌入到 XML 中,而不是整个内容。StringIO
instance is like a file, not like a string. It does not have alen()
. Usemy_string_io_varaible.getvalue()
to get the string value, and pass it tourlencode()
which expects a string.Maybe you could
urlencode
URLs that you embed into the XML along the way, instead of the whole thing.您可以通过调用 StringIO 的 getvalue() 方法从 StringIO 获取字符串,并将其传递给 urllib。
You can get a string from your StringIO by calling its getvalue() method, and pass that to urllib.