上传1GB文件到GCP Storage出现超时错误,Python代码如何解决?
GCP Storage 1GB大文件上传超时解决方案
该错误是大文件单请求上传时的网络连接超时导致,默认上传逻辑未启用分块传输,单次请求需要在短时间内传输完1GB数据,网络稍有波动就会触发超时。可按以下方案优化:
- 启用分块可恢复上传:给blob对象设置
chunk_size参数,建议设置为3210241024(即32MB,需为256KB的整数倍),SDK会自动将文件拆分为多个分块依次上传,单个分块上传失败只会重试对应分块,不需要重传整个文件。 - 上调请求超时阈值:调用
upload_from_filename时传入timeout参数,建议设置为300(单位秒,可根据自身网络情况调整),避免单次请求超时时间过短。 - 配置自动重试策略:针对连接超时、网络中断等异常,给上传方法传入
retry参数,使用SDK内置的重试规则覆盖默认配置,自动重试可恢复的网络错误。
修改后的核心代码如下:
# 提前导入依赖 import requests from google.api_core.retry import Retry import google.api_core.exceptions def upload_file_to_gcs(local_filepath:str, bucket_name:str, gcs_filepath:str = None): if local_filepath == None: raise ValueError("local_filepath cannot be None") if not os.path.isfile(local_filepath) or not os.path.exists(local_filepath): raise TypeError(f"{local_filepath} is not a file or does not exist.") if bucket_name == None: raise ValueError("bucket cannot be None") if not bucket_exist(bucket_name): logging.info(f"Bucket {bucket_name} does not exist. Creating...") create_bucket(bucket_name) logging.info(f"Uploading {local_filepath} to GCS...") # Initialise a client storage_client = storage.Client() if gcs_filepath == None: gcs_filepath = Path(local_filepath).name #create bucket object bucket = storage_client.get_bucket(bucket_name) # 创建blob时指定分块大小 32MB blob = bucket.blob(gcs_filepath, chunk_size=32*1024*1024) # 自定义重试规则,适配网络类错误 custom_retry = Retry( total=10, # 最多重试10次 backoff_factor=2, # 指数退避系数 retry_multiplier=2, exceptions=[ requests.exceptions.ConnectionError, requests.exceptions.Timeout, google.api_core.exceptions.InternalServerError, google.api_core.exceptions.BadGateway, google.api_core.exceptions.ServiceUnavailable, google.api_core.exceptions.GatewayTimeout ] ) # 上传时传入超时和重试参数 uploaded_file = blob.upload_from_filename( local_filepath, timeout=300, retry=custom_retry ) logging.info(f"Uploaded {local_filepath} to {bucket_name} in GCS.") return vars(blob)
如果你的网络环境较差,可适当降低分块大小到16MB,同时拉长超时时间到600秒即可正常上传。
内容的提问来源于stack exchange,提问作者slashie
相关产品推荐
相关产品推荐

