python主线程执行_在Django vi中的主线程中执行Python函数
我創(chuàng)建了Django視圖“graph”,目的是顯示從matplotlib.pyplot模塊。我編寫(xiě)了我的函數(shù)plot\u bubbles(返回amatplotlib.figure.figure對(duì)象)在腳本數(shù)據(jù)中_分析.py導(dǎo)入到視圖.py腳本。在
Tkinter只能在主線程上運(yùn)行,我的網(wǎng)頁(yè)在我第一次請(qǐng)求時(shí)按預(yù)期工作,但在刷新或再次請(qǐng)求時(shí)它不顯示圖像。我的理解是,當(dāng)視圖再次被請(qǐng)求時(shí),Django在一個(gè)新線程上操作代碼。在from django.http import HttpResponse
from . import data_analysis
import Queue
import threading
q = Queue.Queue()
def graph(request):
parties = ["Conservative Party", "Labour Party", "Green Party", "UKIP"]
def from_other_thread(graph_function):
q.put(graph_function)
def main_thread_execute():
callback = q.get()
fig = callback
return fig
def grapher(arguments, area_variable):
data_analysis.plt.close('all')
from_other_thread(data_analysis.plot_bubbles(arguments, area_variable))
t = threading.Thread(target = grapher, args=(parties, data_analysis.all_data['2015 Pay']))
t.start()
t.join()
fig = main_thread_execute()
response = HttpResponse(content_type='image/png')
fig.savefig(response, format='png')
return response
其目的是在主線程中運(yùn)行函數(shù),以便Tkinter可以實(shí)際工作并創(chuàng)建圖像我希望每次請(qǐng)求url時(shí)都創(chuàng)建圖像,因?yàn)槲覍⒃试S用戶(hù)通過(guò)表單選擇他想要可視化的變量,并將它們作為plot_bubbles函數(shù)的參數(shù)傳遞。在
我是django的初學(xué)者,從未在代碼中使用過(guò)多線程,感謝您閱讀本文。如有任何關(guān)于您的解決方案的解釋,我們將不勝感激。在
編輯
不一定需要穿線。問(wèn)題源于我的數(shù)據(jù)分析腳本生成繪圖的方式。尤其是方法調(diào)用的代碼matplotlib.pyplot.subplothttp://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots生成一個(gè)帶有4個(gè)軸對(duì)象的圖形
^{pr2}$
這似乎導(dǎo)致Tkinter無(wú)法在主循環(huán)上運(yùn)行,我還沒(méi)有完全理解原因。這就是代碼現(xiàn)在的樣子#!/usr/bin/python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from pandas import Series, DataFrame
from pylab import figure, axes, plot, title, subplots
import statsmodels.api as sm
from sqlalchemy import create_engine
from matplotlib.backends.backend_agg import FigureCanvasAgg
import matplotlib
# Load data from database into dataframe
engine = create_engine("postgresql://user_name:password@localhost:5432/brexit")
all_data = pd.read_sql('''SELECT * FROM records;''', engine, index_col='Borough')
# Bubble Plot function creation
colors = np.random.rand(len(all_data.index))
area = []
def plot_bubbles(arguments, area_variable, space=0):
ah = iter(arguments)
eh = iter(arguments)
ih = iter(arguments)
kh = iter(arguments)
th = iter(arguments)
zh = iter(arguments)
mh = iter(arguments)
fig = figure(figsize=(30, 25))
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
collection = [ax1, ax2, ax3, ax4]
for x in area_variable:
#want the bubbles to have an average area of 40, add a factor to increase the variability in size
factor = ((x-area_variable.mean())**2/400)
area.append(factor*x*(40/area_variable.mean()))
for ax in collection:
orient = all_data[ah.next()]
ax.set_ylabel('Leave %')
ax.set_xlim([max(0, all_data[zh.next()].min()-all_data[mh.next()].min()/3),
all_data[ih.next()].max()+all_data[th.next()].max()/7])
results = sm.OLS(all_data['Leave votes'], sm.add_constant(orient)).fit()
X_plot = np.linspace(orient.min()-0.05, orient.max(), 100)
ax.plot(X_plot, X_plot*results.params[1] + results.params[0], )
for label, ori, leave in zip(all_data.index, orient, all_data['Leave votes']):
ax.annotate(label, xy=(ori, leave), xytext=(ori, leave+0.05),
arrowprops={'facecolor':'black', 'connectionstyle':'arc3,rad=0.3', 'arrowstyle':'simple'})
ax.scatter(orient, all_data['Leave votes'], s=area, c=colors, alpha=0.6)
ax.set_title(kh.next())
fig.subplots_adjust(hspace=space, wspace=space)
return fig
隨著圖形和軸創(chuàng)建方式的改變,問(wèn)題得到了解決。如果有人能解釋一下為什么會(huì)這樣,那就很有趣了。在
總結(jié)
以上是生活随笔為你收集整理的python主线程执行_在Django vi中的主线程中执行Python函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 联想小新Air 14酷睿版开启预售:直降
- 下一篇: 5000元来一台高性价比大屏轻薄本:三选