将Python信息发送到JavaScript文件

3

我对Python和JavaScript都很陌生,但我正在尝试使用cola.js。我的HTML表单将信息发送给Python,然后将其转换为字典数组。

Class_Name(ndb.Model):
    class_title = ndb.JsonProperty()
def post(self):
    classname = self.request.get('classname') #user inputs 1 classname
    prereq = self.request.get('prereq') #user inputs 1 prereq
    new_dictionary = {}
    new_dictionary [classname] = prereq
    new_class = Class_Name(class_title = new_dictionary) #stores as a dictionary
    new_class.put()

    Class_data = Class_Name.query().fetch() #gets all instances of Class_Name

   *** code that goes in b/w sends back to input form if want to add more classes, else, goes to below code

        output = []
        for a in Class_data:
            jsonprop = a.class_title
            extracted_output = json.dumps(jsonprop)
            output.append(extracted_output)
        template_vars= {'Class_data': output}
        template = jinja2_environment.get_template('template/post.html')
        self.response.write(template.render(template_vars))

这是我目前的基本代码。我想用cola.js将我的信息转换成图形,基本上将每个班级及其先修课程映射出来。然而,cola.js的格式是一个JavaScript文件,看起来像这样:
graph = {
  nodes: [
  {
    id: 'A'
  }, {
    id: 'B'
  }, {
    id: 'C'
  }
],

links: [
  {
    id: 1,
    source: 'A',
    target: 'B'
  }, {
    id: 2,
    source: 'B',
    target: 'C'
  }, {
    id: 3,
    source: 'C',
    target: 'A'
  }
]
};

有没有办法让 JavaScript 获取我的 Python 数组,并像这样将信息输入到 JavaScript 文件中?
graph = {
  nodes: [
  {
    id: 'Class1' **will put actual class name
  }, {
    id: 'Class2'
  }
],

links: [
  {
    id: 1,
    source: 'Class1',
    target: 'prereq'
  }, {
    id: 2,
    source: 'Class2',
    target: 'prereq'
  }
]
};

这是将我的Python信息转换为JavaScript格式的粗略代码。

nodes_array = []
nodes_dict = {}
links_array = []
links_dict = {}
graph_array = []

#loops through every element
for a in Class_data:
    jsonprop = a.class_title
    extracted_output = json.loads(jsonprop)

for c_class, prereq in extracted_output.iteritems():
    # for the links dictionary  
    counter_link = 1
    # creates {'id':'class1'}
    nodes_dict['id'] = c_class
    #creates [ {'id':'class1'},  {'id':'class2'}]
    nodes_array.append(nodes_dictionary)
    # creates {'id': 'counter', 'source': 'class1', 'target': 'prereq'}
    links_dictionary[id] = counter_link
    counter_link++
    links_dictionary[source] = c_class
    links_dictionary[target] = prereq
    # creates [{'id': 'counter', 'source': 'class1', 'target': 'prereq'}]
    links_array.append(links_dictionary)
    #creating the format --> 'nodes': [  {id: class1}, {id:class2},  {id:class3} ]"
    #creating the format --> 'links': [  {id: 1, source :class2, target :class3} ]"
    graph[nodes] = nodes_array
    graph[links] = links_array

你可以通过编程方式生成JavaScript文件;但通常更好的解决方案是使用JavaScript,例如 jQuery.ajax()来获取数据。 - Antti Haapala -- Слава Україні
也许您正在寻找这个:https://dev59.com/U1rUa4cB1Zd3GeqPhCVF - Allen Fernandes
1个回答

2
您的Python脚本可以使用 json模块将图形以JavaScript可理解的格式写入文件。
如果您在Python中这样做:
import json

graph = {
    'nodes': [ {'id': 'Class1'}, {'id': 'Class2'} ],
    'links': [
        { 'id': 1, 'source': 'Class1', 'target': 'prereq' },
        { 'id': 2, 'source': 'Class2', 'target': 'prereq' }
    ]
}

with open('graph.js', 'w') as out_file:
  out_file.write('var graph = %s;' % json.dumps(graph))

结果是一个名为graph.js的文件,其中包含以下内容:
var graph = {"links": [{"target": "prereq", "source": "Class1", "id": 1}, {"target": "prereq", "source": "Class2", "id": 2}], "nodes": [{"id": "Class1"}, {"id": "Class2"}]};

如果在加载自己的 JavaScript 文件之前加载 graph.js,则可以引用变量graph来使用你的图形。

谢谢之前的评论!我会尝试做这个,看看是否会遇到任何问题。 - amay20
如果您对我的回答感到满意,能否请您接受它呢? - Michael Laszlo
我更新了代码并想知道如何将我的字典格式化为 {id: 'class'} 而不是 {"id':'class"},这是我从文件中得到的。您还有关于我的代码的任何提示吗?谢谢。 - amay20
{ id: 'class' } 和 { "id": "class" } 之间在语义上没有任何区别。JavaScript 对它们的处理方式完全相同。就文件而言,这是 JSON 所要求的语法。我不知道为什么双引号会让您困扰,但如果确实如此,您不能使用这种简单的方法。您必须编写自己的 Python 代码以生成所需格式的输出。我认为这样做可能不值得努力。您的代码看起来还不错。如果您对它有具体问题,您可能应该发布另一个问题。我的回答是否已经令您满意了呢? - Michael Laszlo
我不懂任何JavaScript,所以我认为JavaScript必须具有特定的语法才能使代码运行。非常感谢您的所有帮助! - amay20

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接