【问题标题】:RuntimeError: main thread is not in main loop using Matplotlib with DjangoRuntimeError:主线程不在使用 Matplotlib 和 Django 的主循环中
【发布时间】:2020-11-03 14:25:56
【问题描述】:

我正在创建一个 Matplotlib 图,以在我的 Django 应用程序的 HTML 模板中显示。我将此图发送到 HTML,方法是将其保存在我的静态文件下,然后使用保存的 .png 加载 img 标记。 在获得对图的引用后,我在 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)

我的 HTML 是这样的:

<img src={% static analysis_figure %} alt="">

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

【问题讨论】:

    标签: python django matplotlib django-templates html-injections


    【解决方案1】:

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

    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    

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

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

    【讨论】:

      【解决方案2】:
      import matplotlib
      matplotlib.use('Agg')
      import matplotlib.pyplot as plt
      
      
      plt.bar(x, y, tick_label = tick_label, 
      width = 0.8, color = ['red','yellow', 'green']) 
          
      
      plt.xlabel('x - axis') 
      
      plt.ylabel('y - axis') 
      
      plt.title('My bar chart!') 
      
      plt.style.use('fivethirtyeight')
          
      fig=plt.gcf()
      plt.close()
      
      `enter code here`# convert graph
      buf=io.BytesIO()
      fig.savefig(buf,format='png')        
      buf.seek(0)
      string =base64.b64encode(buf.read())
      
      uri=urllib.parse.quote(string)
      
      context={'imgdata':uri}
      

      【讨论】:

      • 嗨,艾米,谢谢您的回答。您能否在您的代码中添加一些 cmets?
      • 是的,我正在使用 Matplotlib 包,它在运行时生成一个图形,我从 Matplotlib 图像对象更改为普通的 PNG 图像,然后我插入到我的 django web 应用程序中。在这里,每次图形图像随着我的网站频繁变化,所以我转换为二进制图像对象和运行时本地存储为图像!然后我从 URI 获取位置地址。这些是我完成的,因为图表结果正在改变我们必须更新这就是为什么!
      • 谢谢,这很有道理,我只是问,因为我正在查看您的答案,我认为解释可能有用。顺便提一句。我没有否决你的回答。
      猜你喜欢
      • 2019-03-21
      • 2018-09-29
      • 2013-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多