日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python主线程执行_在Django vi中的主线程中执行Python函数

發(fā)布時間:2023/12/10 python 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python主线程执行_在Django vi中的主线程中执行Python函数 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

我創(chuàng)建了Django視圖“graph”,目的是顯示從matplotlib.pyplot模塊。我編寫了我的函數(shù)plot\u bubbles(返回amatplotlib.figure.figure對象)在腳本數(shù)據(jù)中_分析.py導入到視圖.py腳本。在

Tkinter只能在主線程上運行,我的網(wǎng)頁在我第一次請求時按預期工作,但在刷新或再次請求時它不顯示圖像。我的理解是,當視圖再次被請求時,Django在一個新線程上操作代碼。在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

其目的是在主線程中運行函數(shù),以便Tkinter可以實際工作并創(chuàng)建圖像我希望每次請求url時都創(chuàng)建圖像,因為我將允許用戶通過表單選擇他想要可視化的變量,并將它們作為plot_bubbles函數(shù)的參數(shù)傳遞。在

我是django的初學者,從未在代碼中使用過多線程,感謝您閱讀本文。如有任何關于您的解決方案的解釋,我們將不勝感激。在

編輯

不一定需要穿線。問題源于我的數(shù)據(jù)分析腳本生成繪圖的方式。尤其是方法調(diào)用的代碼matplotlib.pyplot.subplothttp://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots生成一個帶有4個軸對象的圖形

^{pr2}$

這似乎導致Tkinter無法在主循環(huán)上運行,我還沒有完全理解原因。這就是代碼現(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)建方式的改變,問題得到了解決。如果有人能解釋一下為什么會這樣,那就很有趣了。在

總結

以上是生活随笔為你收集整理的python主线程执行_在Django vi中的主线程中执行Python函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。