简体   繁体   English

如何在Python中对base64编码的缓冲读取进行编码?

[英]How do I base64 encode a buffered read in Python?

I'm streaming a png to the browser for use in an img src attribute. 我正在将png流式传输到浏览器,以用于img src属性。

def streamer():
        with open(local_path) as fh:
            while True:
                rbuf = fh.read(READ_BUF_SIZE)
                if not rbuf:
                    break
                yield rbuf

I want to do something like this: 我想做这样的事情:

base64.b64encode(streamer())

But I'm not able to encode a generator. 但是我无法编码生成器。

for part in streamer():
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
    print base64.b64encode(part)
    print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"

base64.b64encode requires bytes or a string (depending on the Python version). base64.b64encode需要字节或字符串(取决于Python版本)。

If you don't mind reading the entire file into memory, first create the full string and then encode it: 如果您不介意将整个文件读入内存,请首先创建完整的字符串,然后对其进行编码:

base64.b64encode(''.join(streamer()))

If you want to encode as you go, just be careful to encode in multiples of three bytes. 如果您想随身进行编码,请小心以三个字节的倍数进行编码。 (Three bytes becomes four characters in base64, so you won't have padding issues.) (在base64中,三个字节变为四个字符,因此不会出现填充问题。)

Eg, using a multiple of three as READ_BUF_SIZE , this should work: 例如,使用三的倍数作为READ_BUF_SIZE ,这应该可以工作:

for part in streamer():
    yield base64.b64encode(part)

The last part should be the only one that's not a multiple of three bytes, so it should be the only one that gets padding (as expected). 最后一部分应该是唯一一个不是三个字节的倍数的部分,因此它应该是唯一得到填充(如预期的那样)的部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM