【发布时间】:2020-08-27 09:00:22
【问题描述】:
我正在尝试使用他们的教程here 中概述的分块将一个大文件上传到谷歌存储。我正在使用 Python(Flask) 和他们的 JSON REST api,因为我的用例不能与现有的没有很好记录的 python 包一起使用。文件块来自浏览器前端的 dropzone。
下面是我的代码(部分代码)
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
scopes=['https://www.googleapis.com/auth/cloud-platform'])
def start_resumable_upload_session(name, mime_type):
"""
Name is the filename for the new object being uploaded
"""
url = f"https://storage.googleapis.com/upload/storage/v1/b/test-bucket-alpha-1/o?uploadType=resumable&name={name}"
headers = {
"X-Upload-Content-Type":mime_type
}
# "X-Upload-Content-Length":"262144"
#prep an authenticated session to make requests
authed_session = AuthorizedSession(credentials)
resp = authed_session.post(url, headers=headers)
if resp.status_code == 200:
return resp.headers.get('Location',None)
else:
return None
authed_session = AuthorizedSession(credentials)
sess_uri = start_resumable_upload_session(file_chunk.filename, file_chunk.content_type)
cn_length = len(file_chunk.read())
tot_size = int(request.form.get("dztotalfilesize"))
headers = {
"Content-Length": str(cn_length),
"Content-Range": f"bytes 0-{str(cn_length-1)}/{str(tot_size-1)}"
}
resp = authed_session.put(sess_uri,data=file_chunk.read(), headers=headers)
响应文本是Failed to parse Content-Range header,甚至当我尝试调整输入以进行调试时,也没有产生响应并且请求只是超时。
我的逻辑可能做错了什么?我也很欣赏代码 sn-ps 的链接,这些链接可能会有所帮助。
更新 - 已解决 正如下面评论中指出的,正确的标题应该是:
headers = {
"Content-Length": str(cn_length),
"Content-Range": f"bytes 0-{str(cn_length-1)}/{str(tot_size)}"
}
即,如果一个对象是 1000 字节,您的范围将从 0 到 999,但总体大小仍应为 1000。
【问题讨论】:
-
我不完全确定,但
tot_size-1看起来像是个错误。对于零字节对象,大小将为 -1,这将是无效的标头。你能打印生成的内容范围标题以确保它有意义吗? -
是的@BrandonYarbrough,结果证明是错误。谢谢。
标签: python flask file-upload google-cloud-storage