gpt4 book ai didi

python - Flask 不释放内存

转载 作者:太空狗 更新时间:2023-10-29 20:31:19 27 4
gpt4 key购买 nike

在开始这个问题时,我会指出我是网络开发的新手。

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

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

编辑 这是我的 View 函数之一。它所做的是使用 SQLAlchemy 从数据库加载数据,然后进行一些时间序列操作(例如内核密度估计和计算累积返回)并输出连接的 div bokeh图形的script字符串,即以_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 中提供的解决方案, 通过在每次调用绘图接口(interface)和函数之后添加一个 gc.collect()

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

但是内存还没有释放。

最佳答案

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

关于python - Flask 不释放内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34794863/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com