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.
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 thesizeconstraint.What you just encoded, when called, returns a “generator function” — obviously no good. Assuming
datais 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
dataof yours comes from — let’s assume you meanself.datainstead. Then you need to keep track, in other instance variables, of the current index intoself.dataand 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
structandarray.