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?
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)))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.