Python 将 JSON 对象从 Flask 传递给 JavaScript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42499535/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:47:39  来源:igfitidea点击:

Passing a JSON object from Flask to JavaScript

javascriptpythongoogle-mapsflaskjinja2

提问by BrettJ

I'm having troubles getting a Flask/Python variable passed to Javascript.

我在将 Flask/Python 变量传递给 Javascript 时遇到了麻烦。

Basically, I'm importing from MySQL and have tried rendering the return in three different ways.

基本上,我从 MySQL 导入并尝试以三种不同的方式呈现返回。

  1. (43.8934276, -103.3690243), (47.052060, -91.639868), (45.1118, -95.0396)that is the output when my dict item has the following ran on it.
  1. (43.8934276, -103.3690243), (47.052060, -91.639868), (45.1118, -95.0396)这是当我的 dict 项目在其上运行以下内容时的输出。

new_list = [tuple(d.values()) for d in MySQL_Dict] output = ', '.join('(' + ', '.join(i) + ')' for i in new_list)

new_list = [tuple(d.values()) for d in MySQL_Dict] output = ', '.join('(' + ', '.join(i) + ')' for i in new_list)

This method is no good, but I added it for detail, it's not in the right format at all.

这种方法不好,但是我添加了它的详细信息,它的格式根本不正确。

  1. I pass the python dict directly to the template which looks like this
  1. 我将python dict直接传递给看起来像这样的模板

({'lat': '43.8934276', 'lng': '-103.3690243'}, {'lat': '47.052060', 'lng': '-91.639868'}, {'lat': '45.1118', 'lng': '-95.0396'})

({'lat': '43.8934276', 'lng': '-103.3690243'}, {'lat': '47.052060', 'lng': '-91.639868'}, {'lat': '45.1118', 'lng': '-95.0396'})

Then on the the template side I've tried the following JavaScript lines

然后在模板方面,我尝试了以下 JavaScript 行

 var other_coords = {{ MySQL_Dict|tojson }}; 
 var other_coords = {{ MySQL_Dict|tojson|safe }};
 var still_more = JSON.parse(other_coords);

None of which work, together or separately.

这些都不起作用,无论是一起还是分开。

  1. I've also tried sending the dictionary from the view using json_out = json.dumps(My_Dict)which does not work either.
  1. 我也试过从视图中发送字典,使用json_out = json.dumps(My_Dict)which 也不起作用。

This is all with the goal of getting the lat, lng coords from the MySQL DB to the Google Maps API script. The thing that is so confusing to me is that if I just paste the json.dump results from the view into the Google Maps script it works perfectly (after the quotes are removed) but if I use a variable it will not work for me. Does anyone have suggestions?

这一切都是为了从 MySQL DB 到 Google Maps API 脚本获取经纬度坐标。令我感到困惑的是,如果我只是将视图中的 json.dump 结果粘贴到 Google Maps 脚本中,它可以完美运行(删除引号后),但如果我使用变量,它将对我不起作用。有没有人有建议?

回答by Ilya V. Schurov

It seems that the currently accepted answer (by @BrettJ) has a possible security flaw in it: if the object we pass to javascript has some string with a single quote inside, this single quote will not be escaped by json.dumps, thus allowing to inject arbitrary code into javascript. It is better to use Flask's tojson()template filter, see the docs, as it makes proper escaping of all such characters (replace them with unicode codes).

目前接受的答案(@BrettJ)似乎存在一个可能的安全漏洞:如果我们传递给 javascript 的对象有一些带有单引号的字符串,则该单引号不会被 转义json.dumps,从而允许注入任意编码成javascript。最好使用 Flask 的tojson()模板过滤器,请参阅docs,因为它可以正确转义所有此类字符(将它们替换为 unicode 代码)。

Here is my solution:

这是我的解决方案:

view.py

查看.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    user = {'firstname': "Mr.", 'lastname': "My Father's Son"}
    return render_template("index.html", user=user)

if __name__ == '__main__':
    app.run()

index.html

索引.html

<p>Hello, <span id="username"></span></p>
<script>
    var user = JSON.parse('{{ user | tojson | safe}}');
    document.getElementById('username').innerHTML = user.firstname + " " +
            user.lastname;
</script>

Generated JS looks like:

生成的 JS 看起来像:

var user = JSON.parse('{"firstname": "Mr.", "lastname": "My Father\u0027s Son"}');

which is perfectly safe. For example, if we'd use json.dumps-powered solution, we'd get

这是完全安全的。例如,如果我们使用json.dumps-powered 解决方案,我们会得到

var user = JSON.parse('{"firstname": "Mr.", "lastname": "My Father's Son"}');

which is syntactically incorrect (to say the least).

这在语法上是不正确的(至少可以这么说)。

回答by Matt Healy

The below simple example should show how to get a Javascript object from your dict:

下面的简单示例应该展示如何从您的 dict 中获取 Javascript 对象:

views.py

视图.py

@app.route('/', methods=['GET','POST'])                                         
def index():                                                                    

    points = [{"lat": 43.8934276, "lng": -103.3690243},                         
              {"lat": 47.052060, "lng": -91.639868},                            
              {"lat": 45.1118, "lng": -95.0396}]                                

    return render_template("index.html", points=json.dumps(points)) 

index.html(some code removed for brevity)

index.html(为简洁起见删除了一些代码)

  function initMap() {                                                      

    var map = new google.maps.Map(document.getElementById('map'), {         
      center: new google.maps.LatLng(43.8934276, -103.3690243),             
      zoom: 4                                                               
    });                                                                     

    var points = JSON.parse('{{ points|safe }}');                           
    var marker;                                                             

    for (var i = 0; i < points.length; i++) {                               

        marker = new google.maps.Marker({                                   
          position: new google.maps.LatLng(points[i].lat, points[i].lng),   
          map: map                                                          
        });                                                                 

    }                                                                       
  }