2017-09-01 82 views
0

我試圖學習如何將我的Highchart從python腳本轉移到Django。我一直在使用this solution thread去那裏(但迄今爲止徒勞無功)。將python的腳本對象傳遞給Django的views.py

我得叫script.py返回名爲chart_data對象的Python腳本。現在在Django中,我想在我的views.py中執行一個函數來執行script.py文件,抓住對象的chart_data並將其分配給一個名爲'data'的新對象。

我的script.py文件存儲在/ scripts /目錄下的我的項目根目錄下,它包含自己的__init__.py文件。

使用下面的代碼服務器返回一個錯誤,指出:全局名稱'chart_data'未定義

任何解釋,我在做什麼錯在這裏將不勝感激。

### views.py 

from __future__ import unicode_literals 
import datetime 
import subprocess 
import scripts 

def plot(request, chartID = 'chart_ID', chart_type = 'line', chart_height = 500): 

    raw = subprocess.Popen('~/scripts/script.py', shell=True) 

    data = chart_data 

    chart = {"renderTo": chartID, "type": chart_type, "height": chart_height,} 
    title = {"text": 'my title here'} 
    xAxis = {"title": {"text": 'xAxis name here'}, "categories": data['Freq_MHz']} 
    yAxis = {"title": {"text": 'yAxis name here'}} 
    series = [ 
    {"name": 'series name here', "data": data['series name here']}, 
    ] 

    return render(request, '/chart.html', {'chartID': chartID, 'chart': chart, 
               'series': series, 'title': title, 
               'xAxis': xAxis, 'yAxis': yAxis}) 

回答

1

是,chart_data未在此代碼的任何地方定義。

您似乎將腳本作爲外部進程運行,然後期待Django會以某種方式知道它定義的變量。這不是它的工作原理。

而不是通過Popen調用你的腳本,你應該導入它就像你使用的其他Python模塊。然後你可以調用它的任何函數,並將它們的返回值分配給任何你喜歡的。

0

把你的腳本,你正在使用的Django應用程序內,然後將其導入:

from my_app.chart_data import chart_data