Flask jsonify: how to escape characters

﹥>﹥吖頭↗ 提交于 2020-01-01 19:18:47

问题


I have just started working with the Flask web framework. I am currently writing an endpoint that returns bits of JSON that may very well contain malicious javascript.

For example:

@api.route("/tester")
def api_jobs_tester():
    return jsonify({
        "name": "<script>alert(1)</script>"
    })

In this example, this returns:

{
  "name": "<script>alert(1)</script>"
}

Ideally, however, I would like this to return:

{
  "name": "&lt;script&gt;alert(1)&lt;/script&gt;"
}

Of course, this is straightfoward to do on a per-value, basis, with just:

return jsonify({
    "name": escape("<script>alert(1)</script>")
})

However, I may need to return much more complex JSON responses than this, in which I do not necessarily know before hand the structure of the JSON.

I could probably role my own function that traverses the JSON tree and escapes all the strings, but I would much prefer a built-in way of doing this.

What is the easiest way to escape the values in a JSON response using Flask?


回答1:


jsonify function haven't option for escaping. But there is htmlsafe_dumps function in flask.json which you can use:

from flask import json, jsonify

return jsonify(**json.loads(json.htmlsafe_dumps(obj)))


来源:https://stackoverflow.com/questions/27369306/flask-jsonify-how-to-escape-characters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!