用于编码 URL 的 urllib.urlencode 的替代方案

发布于 2024-12-22 06:43:21 字数 760 浏览 5 评论 0原文

我正在尝试向仅接受 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

这样的小城市 2024-12-29 06:43:21

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 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.

画离情绘悲伤 2024-12-29 06:43:21

您可以通过调用 StringIO 的 getvalue() 方法从 StringIO 获取字符串,并将其传递给 urllib。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文