问题
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": "<script>alert(1)</script>"
}
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