Python操作Google Cloud Storage从bytes对象上传文件失败求助
错误原因分析
upload_from_file报错:该方法要求传入类文件对象(需实现read()、tell()等方法,如本地文件句柄、BytesIO实例),直接传入bytes对象不满足参数要求,因此触发AttributeError: 'bytes' object has no attribute 'tell'。upload_from_string报错:旧版本的google-cloud-storageSDK对二进制内容的upload_from_string调用存在兼容问题,会出现类型转换错误。
解决方案
最优方案(适配BytesIO生成PDF的场景)
不要将BytesIO转成bytes对象,直接复用BytesIO实例上传,只需在生成PDF后将读写指针移到开头即可:
from io import BytesIO from google.cloud import storage # PDF生成逻辑 pdf = BytesIO() pisa.CreatePDF(html, pdf) # 关键步骤:将BytesIO指针移到文件开头,否则上传的内容为空 pdf.seek(0) # GCS上传逻辑 storage_client = storage.Client() bucket = storage_client.bucket("bucket_name") blob = bucket.blob("destination_blob_name") # 直接传入BytesIO实例 blob.upload_from_file(pdf, content_type='application/pdf') pdf.close()
已有bytes对象的场景
如果你已经拿到了PDF的bytes内容,可将其重新包装为BytesIO实例后上传:
# resp为已生成的PDF bytes对象 pdf_file = BytesIO(resp) blob.upload_from_file(pdf_file, content_type='application/pdf') pdf_file.close()
适配upload_from_string的场景
先升级SDK到最新版本:pip install --upgrade google-cloud-storage
再直接传入bytes对象即可:
blob.upload_from_string(resp, content_type='application/pdf')
内容的提问来源于stack exchange,提问作者Charlie Morton
相关产品推荐
相关产品推荐

