这是从谷歌云存储中将zip文件加载到内存中的正确用法吗?

时间:2014-01-11 15:20:35

标签: python google-app-engine google-cloud-storage

在我的python web应用程序中从GCS加载文件后,我收到了奇怪的HTTP错误。

suspended generator urlfetch(context.py:1214) raised DeadlineExceededError(Deadline exceeded while waiting for HTTP response from URL: https://storage.googleapis.com/[bucketname]/dailyData_2014-01-11.zip)

但是,根据应用程序在下面记录的内容,它已经加载了文件(并且基于内存使用情况,似乎在内存中)。

bucket = '/[bucketname]'
filename = bucket + '/dailyData'+datetime.datetime.today().strftime('%Y-%m-%d')+'.zip'
gcs_file = gcs.open(filename,'r')
gcs_stats = gcs.stat(filename)
logging.info(gcs_stats)
zip_file = zipfile.ZipFile(gcs_file, 'r')
logging.info("zip file loaded")

有没有办法我应该关闭HTTP请求,或者它实际上是不是从内存加载zip_file而是试图一直从GCS中提取......?谢谢!

1 个答案:

答案 0 :(得分:1)

您应确保关闭正在打开的文件。您可以使用with上下文,当文件超出范围时会自动关闭该文件:

bucket = '/[bucketname]'
filename = bucket + '/dailyData'+datetime.datetime.today().strftime('%Y-%m-%d')+'.zip'
gcs_stats = gcs.stat(filename)
logging.info(gcs_stats)
with gcs.open(filename,'r') as gcs_file:
  with zipfile.ZipFile(gcs_file, 'r') as zip_file:
    logging.info("zip file loaded")