将JSON对象从Flask传递到JavaScript [英] Passing a JSON object from Flask to JavaScript

查看:142
本文介绍了将JSON对象从Flask传递到JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有麻烦得到一个Flask / Python变量传递给Javascript。

基本上,我从MySQL导入并尝试以三种不同的方式呈现返回。 (43.8934276,-103.3690243),(47.052060,-91.639868),(45.1118,-95.0396),


  1. code>这是我的字典项目具有以下内容时输出的输出。

new_list = [元组(d.values())for MySQL_Dict]
输出=','.join('('+','.join(i)+')'in new_list)



这种方法并不好,但我添加了它的细节,它根本没有正确的格式。


  1. 我直接将python dict传递给模板,看起来像这样

  2. ol>

    ({'lat':'43 .8934276','lng':'-103.3690243'},{'lat':'47 .052060','lng ':'-91.639868'},{'lat':'45 .1118','lng':'-95.0396'})



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

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

    没有一个可以一起或单独使用。


    1. 我也尝试使用 json_out = json.dumps从视图发送字典(My_Dict)这也不起作用。

    这些都是为了将​​MySQL数据库中的lat,lng坐标转换为Google Maps API脚本。对我来说如此令人困惑的事情是,如果我只是将视图中的json.dump结果粘贴到Google Maps脚本中,那么它完美地工作(删除引号后),但如果我使用变量,它将不适用于我。有人有建议吗?解决方案似乎目前接受的答案(by @BrettJ)有一个可能的安全缺陷:如果我们传递给javascript的对象有一些带有单引号的字符串,那么这个单引号不会被 json.dumps 转义,从而允许将任意代码注入到javascript中。最好使用Flask的 tojson()模板过滤器,参见文档,因为它可以正确地转义所有这些字符(用unicode代码替换它们)。



    这是我的解决方案:

    view.py

      from flask flask Flask,render_template 

    app = Flask(__ name__)

    @ app.route('/')
    def hello_world():
    user = {'firstname':Mr.,'lastname':我父亲的儿子}
    返回render_template(index.html,user = user)

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

    index.html

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

    生成的JS看起来像:

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

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

      var user = JSON.parse('{firstname:Mr.,lastname:我的父亲的儿子}'); 

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


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

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

    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.

    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

    ({'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

     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.

    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?

    解决方案

    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).

    Here is my solution:

    view.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

    <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:

    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

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

    which is syntactically incorrect (to say the least).

    这篇关于将JSON对象从Flask传递到JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆