【发布时间】:2021-08-11 10:43:53
【问题描述】:
我向服务器发出 requests.post() 调用,它用 json 回复我,在这个 json 中有一些键和 base64 文件。
这是来自服务器的响应示例:
服务器响应如下:
-
'success'是了解是否使用私有数据访问的关键 正确。 -
'message'是成功为 False 的关键(在这种情况下为 成功 == 真,消息未显示 -
'data'是包含文件名和 base64 格式文件
所以:
{'success': True,
'message': '',
'data': {'fileName': 'Python_logo_and_wordmark.svg.png',
'file': 'iVBORw0KGgoAAAANSUhEUgAABLAAAA....'}} #To limit the space, I cut the very long bytes example
所以json中的respose也包含文件,我需要用base64.b64decode(r.json()['data']['file'])解码
一切正常,我可以得到我的文件并正确解密。
问题是对于大文件,我想使用这样的流方法:
file = "G:\Python_logo_and_wordmark.svg.png"
if os.path.isfile(file):
os.remove(file)
def get_chunk(chunk):
# Try to decode the base64 file (Chunked)
# is this a wrong approach?
chunk = chunk.decode("ascii")
chunk = chunk.replace('"', '')
if "file" in chunk:
chunk = chunk.split('file:')[1]
elif "}}" in chunk:
chunk = chunk.split('}}')[0]
else:
chunk = chunk
chunk += "=" * ((4 - len(chunk) % 4) % 4)
chunk_decoded = base64.b64decode(chunk)
return chunk_decoded
r = requests.post(url=my_url, json=my_data, stream=True)
iter_content = r.iter_content(chunk_size=64)
while True:
chunk = next(iter_content, None)
if not chunk:
break
chunk_decoded = get_chunk(chunk)
with open(file, "ab") as file_object:
file_object.write(chunk_decoded)
iter_content 块返回:
b'{"success":true,"message":"","data":{"fileName":"Python_logo_and'
b'_wordmark.svg.png","file":"iVBORw0KGgoAAAANSUhEUgAABLAAAAFkCAYAA'
b'AAwtsJRAAAABGdBTUEAALGPC\\/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAA'
b'dTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA\\/wD\\/AP+gvaeTAACAAElEQVR42u'
b'zdeZwbdf0\\/8Nf7k2Ovdttyt7QIggoth1qUW1AQ5PLeAiK13UwWiqLiBZ4Eb+T6+'
有时在解码中填充存在固有的错误,但经过 1 周的尝试后,我更愿意在这里问这个问题,因为我害怕在这种情况下采取错误的方法。 我想如何以正确的方式处理这种情况
【问题讨论】:
-
这能回答你的问题吗? Download large file in python with requests
-
Hello @rzlvmp 它看起来很相似,但实际上我的问题是编码文件包含在json响应中,我不必编写json,但我必须编写文件包含在响应中,所以在 {"data": {"file": "b64string"}}
-
您到底遇到了什么错误?你能用 log 解释一下吗?
-
hello @devReddit 我的问题是我害怕对这种情况采取错误的方法,所以我在任何地方都找不到答案。我遇到了各种各样的错误,我也尝试过进行base 64填充,但最后我得到的图像损坏了,所以我发布了我的方法示例以了解这种方法是否真的可以工作,或者非常错误.我找到了很多关于使用方法 stream = True 以块下载文件的答案,但在我的情况下没有示例。
-
@NoobCat 检查我的答案