Python - GAE - 脚本循环消耗大量内存

标签 python google-app-engine memory urlfetch

我正在使用以下脚本创建一些 rss 快照(只是说)。

该脚本在后端运行,我遇到了一些不断增加的内存消耗。

class StartHandler(webapp2.RequestHandler):

    @ndb.toplevel
    def get(self):
        user_keys = User.query().fetch(1000, keys_only=True)
        if not user_keys:
            return
        logging.info("Starting Process of Users")
        successful_count = 0
        start_time = time.time()
        for user_key in user_keys:
            try:
                this_start_time = time.time()
                statssnapshot = StatsSnapShot(parent=user_key,
                                        property=get_rss(user_key.id())
                                        )
                #makes a urlfetch
                statssnapshot.put_async()
                successful_count += 1               
            except:
                pass
        logging.info("".join(("Processed: [",
                            str(successful_count),
                            "] users after [",
                            str(int(time.time()-start_time)),
                            "] secs")))
        return

编辑

这也是 rss 函数:

def get_rss(self, url):
        try:
            result = urlfetch.fetch(url)
            if not result.status_code == 200:
                logging.warning("Invalid URLfetch")
                return
        except urlfetch.Error, e:
            logging.warning("".join("Fetch Failed to get ",url," with",e))
            return
        content = result.content #Around 500 - 200KB
        reobj = re.compile(r'(?<=")[0-9]{21}(?=")')
        user_ids = reobj.findall(content)
        user_ids = set(user_ids)#set to fail if something is not unique
        return user_ids

脚本运行正常,但随着用户数量的增加,脚本消耗的内存也越来越多。 来自 C 我不知道如何在 Python 中高效地操作内存和变量。

例如,我知道如果 python 中的变量不再被引用,垃圾收集器会释放用于该变量的内存,但是我的情况似乎是这样,我在哪里做错了?

如何优化此脚本使其内存使用量不断增加,但仅消耗每个所需内存用户进程?

最佳答案

NDB 添加了自动缓存,这通常非常方便。你有内存缓存和memcached,你可以为它们设置策略。

做看跌期权时,您可以提供context options ,我怀疑以下内容对您有用:

statssnapshot.put_async(use_cache=False)

关于Python - GAE - 脚本循环消耗大量内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14439626/

相关文章:

python - 使用 CVXPY 实现 LMI 约束

string - 德尔福: how to completely remove String from the memory

linux - 如何在 Linux 中获得内存修改通知

c - 分配给 : should I have to free it? 的指针

python - 为什么我的 python 模块不安装?

python - 如何在 python 中打印 3x3 数组?

python - Django:通过 HttpResponse 流式传输动态生成的 XML 输出

python - GAE 中的 SQLAlchemy 'character_set_name' 错误

python - 如何在 GAE 上使用 python 将 XML 文件加载到字符串中?

Python webapp 动态路径