【问题标题】:python dictionary parameter to JS dictionary with flask templates [duplicate]python字典参数到带有烧瓶模板的JS字典[重复]
【发布时间】:2019-10-09 08:56:29
【问题描述】:

我在带有 python3.6 的烧瓶服务器中有一个字典,并希望使用烧瓶模板框架将 dict_test 字典移动为 Javascript 字典。哪条路?

flask-server.py

@app.route("/app", methods=['GET'])
def home():
    dict_test = {"key1":10, "k2":'hello'}
    return render_template("index.html", text_lists=dict_test)


logging.info("Listener started")

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5000)

index.html

    <body>
      <script>
          var tp_data = {{text_lists}};
      </script>
             ....
    </body>

【问题讨论】:

    标签: python flask


    【解决方案1】:

    您可以使用simplejson 将您的字典转换为json:

    return render_template("index.html", text_lists=simplejson.dumps(dict_test))
    

    在您的 index.html 中,您可以像以前一样访问 text_lists

    var tp_data = {{text_lists | safe}};
    

    当您添加 |safe 时,您表示您已经对文本进行了转义,直接渲染它是安全的。

    【讨论】:

    • 我想要一个 Javascript 的字典,simplejson.dumps() 返回一个字符串,对吧?
    • .py 端将其转换为有效的 JSON 对象。我正在使用dumpsignore_nan=True 等一些参数来确保js-object 对我的需要有效。
    【解决方案2】:

    这种方法对我有用:

    flask-server.py

    return render_template("index.html", text_lists=dict_test)
    

    index.html

    var tp_data = {{text_lists | tojson }};
    

    【讨论】:

      猜你喜欢
      • 2014-12-08
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-20
      • 2020-11-08
      相关资源
      最近更新 更多