烧瓶jsonify:如何转义字符 [英] Flask jsonify: how to escape characters
问题描述
例如:
< pre $ @ api.route(/ tester)
def api_jobs_tester():
返回jsonify({$ b $name:< script> ; alert(1)< / script>
))
这会返回:
{
name:< script> alert(1)< / script>
}
然而,理想情况下,我希望返回:
$ p $
{
name:< script& gt; alert(1)& lt; / script& gt;
$ b当然,在每个值的基础上,只需要:
return jsonify({$ b $name:escape(< script> alert(1) < / script>)
})
然而,比这更复杂的JSON响应,在这之前我不一定知道JSON的结构。
我可以使用我自己的遍历JSON树的函数来转义所有的字符串,但是我更喜欢内置的方法。
使用Flask在JSON响应中转义值的最简单方法是什么? / div> jsonify 函数没有选择转义。但是可以使用flask.json中的 htmlsafe_dumps 函数:
from flask import json, jsonify
返回jsonify(** json.loads(json.htmlsafe_dumps(obj)))
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)))
这篇关于烧瓶jsonify:如何转义字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!