英文:
memory usage keeps going up when repeating requests
问题
最近我在编写一个数据库Web服务器,关于Django的工作机制我有一些问题。我在我的view.py中有一个函数如下:
@api_view(['GET'])
def general_plot_strip(request, gene_name, format='image/png'):
pl = GenePlot(gene_name)
if request.method == "GET":
### 这里的stripplot()是一个绘图函数
fig = pl.stripplot()
buf = io.BytesIO()
fig.savefig(buf, format='png')
plt.close('all')
buf.seek(0)
gc.collect()
return FileResponse(buf, content_type='image/png')
当我运行python manage.py runserver
时,这个可以顺利运行,但是当我多次请求相应的URL时,内存使用量只增不减。这是我尝试两次请求该URL的示例。
英文:
Recently I'm writing a database webserver and I have some problems about the django's working machanism. I have a function in my view.py like this:
@api_view(['GET'])
def general_plot_strip(request,gene_name,format = 'image/png'):
pl = GenePlot(gene_name)
if request.method == "GET":
### here stripplot() is a plot function
fig = pl.stripplot()
buf = io.BytesIO()
fig.savefig(buf, format='png')
plt.close('all')
buf.seek(0)
gc.collect()
return FileResponse(buf, content_type='image/png')
This can run smoothly when running python manage.py runserver
, but when I request the corresponding url for serveral times, the memory usage just goes up and never drops.
This is an example when I try to request the url twice.
答案1
得分: 2
尝试使用上下文管理器 'with' 语句。
@api_view(['GET'])
def general_plot_strip(request, gene_name, format='image/png'):
pl = GenePlot(gene_name)
if request.method == "GET":
fig = pl.stripplot()
with io.BytesIO() as buf:
fig.savefig(buf, format='png')
plt.clf() # 清除当前图形...
plt.close('all')
buf.seek(0)
gc.collect()
return FileResponse(buf, content_type='image/png')
英文:
Try to use a context manager 'with' statement.
@api_view(['GET'])
def general_plot_strip(request,gene_name,format = 'image/png'):
pl = GenePlot(gene_name)
if request.method == "GET":
fig = pl.stripplot()
with io.BytesIO() as buf:
fig.savefig(buf, format='png')
plt.clf() # clear the current figure...
plt.close('all')
buf.seek(0)
gc.collect()
return FileResponse(buf, content_type='image/png')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论