簡體   English   中英

運行時錯誤:主線程不在主循環中使用帶有 Django 的 Matplotlib

[英]RuntimeError: main thread is not in main loop using Matplotlib with Django

我正在創建一個 Matplotlib 圖以顯示在我的 Django 應用程序的 HTML 模板中。 我將這個圖保存在我的靜態文件下,然后將它發送到 HTML,然后加載一個帶有保存的.pngimg標簽。 在獲得對該圖的引用后,我在我的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的函數被第二次調用時發生(如果它在一切正常views.py調用)。 為了防止這個錯誤,我將 Matplotlib 圖形保存到main()以在主線程中運行,然后在我的原始函數中調用它。 這修復了錯誤,但會阻止我的 HTML 重新加載,因此每次用戶提交查詢時,新圖形都會顯示在前一個之上,而不會刪除前一個。 關於任何問題的任何想法?

我認為這篇文章解釋了該怎么做: 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()

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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM