lims, lims_report_html: avoid memory leak when plotting trend charts

This commit is contained in:
Adrián Bernardi 2023-03-14 11:42:26 -03:00
parent 3f824bab23
commit b37f706d66
3 changed files with 23 additions and 0 deletions

View File

@ -6,6 +6,7 @@ import pandas as pd
from io import BytesIO
from math import sqrt
import matplotlib.pyplot as plt
import gc
from trytond.model import ModelView, ModelSQL, fields
from trytond.wizard import (Wizard, StateTransition, StateView, StateAction,
@ -1979,8 +1980,14 @@ class TrendChart(ModelSQL, ModelView):
i += 1
ax.get_figure().savefig(output, bbox_inches='tight', dpi=300)
plt.close('all')
image = output.getvalue()
output.close()
# release memory
del ax, df, df_interpolated
if ds2:
del df2, df2_interpolated
gc.collect()
return image
except (TypeError, ModuleNotFoundError):
@ -2013,12 +2020,23 @@ class TrendChart(ModelSQL, ModelView):
ax.get_figure().savefig(output, bbox_inches='tight',
dpi=300)
plt.close('all')
image = output.getvalue()
output.close()
# release memory
del ax, df, df_interpolated
if ds2:
del df2, df2_interpolated
gc.collect()
return image
except (TypeError, ModuleNotFoundError):
pass
# release memory
del df, df_interpolated
if ds2:
del df2, df2_interpolated
gc.collect()
return output.getvalue()
@classmethod

View File

@ -431,9 +431,12 @@ class LimsReport(Report):
for section in record.following_sections:
filedata = BytesIO(section.data)
merger.append(filedata)
filedata.close()
output = BytesIO()
merger.write(output)
merger.close()
document = output.getvalue()
output.close()
return 'pdf', document

View File

@ -417,6 +417,7 @@ class ResultsReportVersionDetailSample(metaclass=PoolMeta):
open_chart.transition_compute()
plot = tc.chart.get_plot(session_id)
charts.append(plot)
OpenTrendChart.delete(session_id)
div_row = '<div style="clear:both;">'
charts_x_row = int(self.version_detail.charts_x_row) or 1
@ -464,6 +465,7 @@ class ResultsReportVersionDetailSample(metaclass=PoolMeta):
open_chart.transition_compute()
plot = tc.chart.get_plot(session_id)
charts.append(plot)
OpenTrendChart.delete(session_id)
return charts
def _get_resource(self, obj):