【问题标题】:Flask not releasing memory烧瓶不释放内存
【发布时间】:2017-07-13 01:23:12
【问题描述】:

我将首先指出我对 Web 开发非常陌生。

现在重点是:我最近构建了一个相当小的Flask 应用程序,它加载数据,然后使用bokeh 输出数据的可视化。因此,它必须将大量数据存储在内存中(大约 10-20 mb)。这本身并不是一个真正的问题,但是,在视图函数发送请求后,应用程序不会释放内存中的对象。这意味着在仅仅使用几次之后,应用程序就会耗尽大部分内存。

因此,我的问题是:如何在视图函数返回任何请求后强制Flask 释放使用的对象?还是我以错误的方式解决这个问题?值得一提的是,我使用Flask 的内置服务器,因为我们仍然只是原型设计。 ¨ 谢谢,廷吉斯

EDIT 这是我的视图函数之一。它的作用是使用SQLAlchemy 从数据库加载数据,然后进行一些时间序列操作(例如内核密度估计和计算累积回报)并输出divscript 的连接字符串bokeh图,即以_plt结尾的变量。

from app import app
from app.business_logic.classes.interface_classes import Company
from app.business_logic.functions.functions import get_session

@app.route('/analysis_tool/company_performance', methods=['GET', 'POST'])
def analysis_tool__company_performance():
    session = get_session()

    companies_to_analyse = {
        'Company A': {'ts_to_use': 'Returns of Company A'},
        'Company B': {'ts_to_use': 'Returns of Company B'}
    }

    chosen_company = request.form.get('security')
    types_of_plots = {}

    if chosen_company is not None:
        company = Company(session, chosen_company)
        company.load_company()

        company.load_timeseries(companies_to_analyse[chosen_platform]['ts_to_use'])
        company.unpack_observations_of_ts_as_df()

        ret_df = company.manipulate_dataframe('convert timeseries to returns',
                                               frequency='monthly',
                                               ts_type=company.loaded_ts_orm_obj.ts_type_name)
        cum_ret_df = company.manipulate_dataframe('calculate cumulative return', df=ret_df)

        cum_ret_plt = company.plot_dataframe(cum_ret_df, legend=False)
        kde_plt = company.plot_kde(ret_df)

        types_of_plots = {'Cumulative_return': cum_ret_plt, 'KDE': kde_plt}

    return render_template('plotting/plot_using_panels.html',
                           items=sort_dictionary(platforms_to_analyse),
                           plot_types=sort_dictionary(types_of_plots),
                           selected=chosen_company)

这有帮助吗?

EDIT 2我尝试了以下question中提供的解决方案,在每次调用绘图界面以及函数后添加gc.collect()

@app.teardown_request
def teardown_request(exception):
    gc.collect()

但内存仍未释放。

【问题讨论】:

  • 我们至少需要查看一段代码才能了解它为何占用内存。
  • 当然,唯一的麻烦是我今天离开了办公室。我明天可以回复你吗?
  • @DanielCasserly 上面的代码对你有帮助吗,还是你需要更多?
  • 你的get_session函数是做什么的?我感觉这是一个循环类依赖,gc 不知道 del 首先是哪个对象(会话或公司),所以它只是将它们保存在内存中

标签: python flask


【解决方案1】:

您是否可以在 get_session 和 Company 对象之间创建循环引用?

【讨论】:

    猜你喜欢
    • 2010-10-03
    • 1970-01-01
    • 2016-01-03
    • 2017-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 2016-09-14
    相关资源
    最近更新 更多