【问题标题】:Passing a python's script object to Django's views.py将 python 的脚本对象传递给 Django 的 views.py
【发布时间】:2018-02-10 18:04:59
【问题描述】:

我正在尝试学习如何将我的 Highchart 从 python 脚本传输到 Django。我一直在使用this solution thread 到达那里(但到目前为止是徒劳的)。

我有一个名为 script.py 的 Python 脚本,它返回一个名为 chart_data 的对象。现在在 Django 中,我希望我的 views.py 中有一个函数来执行该 script.py 文件,获取 chart_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})

【问题讨论】:

    标签: python django python-2.7 highcharts


    【解决方案1】:

    是的,chart_data 未在此代码中的任何位置定义。

    您似乎将脚本作为外部进程运行,然后期望 Django 以某种方式知道它定义的变量。这根本不是它的工作原理。

    您应该像使用其他 Python 模块一样导入,而不是通过 Popen 调用您的脚本。然后你可以调用它的任何函数并将它们的返回值分配给你喜欢的任何值。

    【讨论】:

      【解决方案2】:

      将您的脚本放入您正在使用的 Django 应用程序中,然后将其导入:

      from my_app.chart_data import chart_data
      

      【讨论】:

        猜你喜欢
        • 2014-06-06
        • 1970-01-01
        • 2016-08-03
        • 1970-01-01
        • 2015-11-22
        • 2013-06-18
        • 1970-01-01
        • 1970-01-01
        • 2012-04-07
        相关资源
        最近更新 更多