【发布时间】:2015-09-26 06:09:54
【问题描述】:
以下是在 Google App Engine 上运行的 Python 代码的一部分。 它使用 cloudstorage 客户端从 Google Cloud Storage 获取文件。
问题是每次代码读取一个大文件(约10M),实例使用的内存会线性增加。很快,由于“在服务 40 个请求后,超过了 128 MB 和 134 MB 的软专用内存限制”,该进程被终止。
class ReadGSFile(webapp2.RequestHandler):
def get(self):
import cloudstorage as gcs
self.response.headers['Content-Type'] = "file type"
read_path = "path/to/file"
with gcs.open(read_path, 'r') as fp:
buf = fp.read(1000000)
while buf:
self.response.out.write(buf)
buf = fp.read(1000000)
fp.close()
如果我注释掉以下行,那么实例中的内存使用情况会发生变化。所以应该是webapp2的问题。
self.response.out.write(buf)
假设webapp2响应完成后会释放内存空间。但在我的代码中,它没有。
【问题讨论】:
-
响应对象只能写入一次。
-
输出流缓冲内存中的所有输出,然后在处理程序退出时发送最终输出。 webapp 不支持将数据流式传输到客户端。您需要用于流式传输的频道 API。
-
我只尝试写入响应对象一次:“buf = fp.read(20000000); self.response.out.write(buf); fp.close();”。但这并不能解决问题
标签: python google-app-engine memory-leaks google-cloud-storage webapp2