带有字节流的 pycurl READFUNCTION
有没有办法为 pycurl 的 READFUNCTION 编写不返回字符串的回调函数?我计划通过 pycurl 发送二进制数据块。我尝试编写一个回调函数来执行此操作:
def read_callback(self, size): for block in data: yield block
但是 pycurl 退出时出现错误,指出返回类型必须是字符串。
Is there a way to write a callback function for pycurl's READFUNCTION that does not return a string? I am planning on sending blocks of binary data via pycurl. i tried writing a callback function that does this:
def read_callback(self, size): for block in data: yield block
but pycurl exits with an error that says the return type must be a string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“读取函数”必须返回一个字节字符串——记住,libcurl 是底层 C 库的包装器,所以当然它是类型挑剔的!-)。然而,它完全可以是一个二进制字节字符串(至少在 Python
2.*
中——我认为 pycurl 无论如何都不能与 Python 3 一起工作),所以它当然可以返回“块二进制数据”——只要它们被编码成字节字符串并遵守大小
约束。您刚刚编码的内容在被调用时会返回一个“生成器函数”——显然没有什么好处。假设
data
是一个非空字节串列表,需要对它进行适当的切块和切片,每次返回一个字节串,用return
,肯定是不是产量
(!)。不确定您的神秘
data
来自哪里——我们假设您指的是self.data
。然后,您需要在其他实例变量中跟踪self.data
的当前索引,并且可能 - 如果项目长于size
- 的“当前作品的“尚未发送的部分”也是如此。例如,它可能是:
如果 self.data 的项目是其他类型的二进制数据(尚未编码为字节字符串),您可以将它们转换为字节字符串,例如借助 Python 库模块(如 struct )的帮助和
数组
。The "read function" must return a string of bytes -- remember, libcurl is a wrapper on an underlying C library, so of course it's type-picky!-). However, it can perfectly be a binary string of bytes (in Python
2.*
at least -- I don't think pycurl works with Python 3 anyway), so of course it can return "blocks of binary data" -- as long as they're encoded into strings of bytes and respect thesize
constraint.What you just encoded, when called, returns a "generator function" -- obviously no good. Assuming
data
is a list of non-empty byte strings, you need to dice and slice it appropriately, returning each time a string of bytes, withreturn
, definitely notyield
(!).Not sure where that mysterious
data
of yours comes from -- let's assume you meanself.data
instead. Then you need to keep track, in other instance variables, of the current index intoself.data
and possibly -- if the items are longer thansize
-- of the "yet unsent part" of the current piece, too.E.g., it could be:
If self.data's items are other kinds of binary data (not already encoded as byte strings), you can turn them into byte strings e.g. with help from Python library modules such as
struct
andarray
.