运行时错误:主线程不在主循环中使用带有 Django 的 Matplotlib

Ahm*_*mad 3 python django matplotlib django-templates html-injections

我正在创建一个 Matplotlib 图以显示在我的 Django 应用程序的 HTML 模板中。我将此图保存在我的静态文件下,然后将其加载到img带有已保存.png. views.py在获得对图的参考后,我在我的中执行此操作。

        # Get analysis visualization chart
        figure = analyser.visualize_tweets(emotions)

        # Save figure in static folder as png
        figure.savefig('static/analysis_figures/figure.png')

        # Inject html with figure path
        response['analysis_figure_path'] = 'analysis_figures/figure.png'

return render(request, 'landing_page/index.html', response)
Run Code Online (Sandbox Code Playgroud)

我的 HTML 是这样的:

<img src={% static analysis_figure %} alt="">
Run Code Online (Sandbox Code Playgroud)

但是,这会导致第二次调用RuntimeError: main thread is not in main loopmy 中的函数时发生views.py(如果一切正常后调用它)。为了防止这个错误,我将保存 Matplotlib 图形移动到main()as 在主线程中运行,然后在我的原始函数中调用它。这修复了错误,但会阻止我的 HTML 重新加载,因此每次用户提交查询时,新图形都会显示在前一个之上,而不会删除前一个。关于任何问题的任何想法?

小智 7

我认为这篇文章解释了该怎么做: How to clean images in Python / Django?

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
Run Code Online (Sandbox Code Playgroud)

如此处所述:https : //matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server

为防止新图形显示在前一个上,请使用: plt.close() / figure.close()