python - 为什么 Flask 在其 json 模块中检查 `'\\/' in json.dumps('/')`?

标签 python flask

The source for the flask.json module contains the following line. '\\/' 是什么意思,为什么 Flask 检查这个?

_slash_escape = '\\/' not in _json.dumps('/')

最佳答案

Flask 正在使用它来测试它使用的 JSON 库是否在不需要时转义斜线。如果图书馆有,那么 json.dump('/')将产生 '"\\/"' (相当于原始字符串 r'"\/"' ,参见 here for an explanation on escape characters )。

Flask 可以选择多个 JSON 库之一,一些库/版本转义正斜杠,而另一些则不转义。 Flask includes a comment explaining this.

如果库确实转义了斜线,Flask will undo this when it dumps the JSON , 为了库之间的一致性。

# figure out if simplejson escapes slashes.  This behavior was changed
# from one version to another without reason.
_slash_escape = '\\/' not in _json.dumps('/')
...
def htmlsafe_dumps(obj, **kwargs):
    ...
    if not _slash_escape:
        rv = rv.replace('\\/', '/')
    ...

Flask still escapes unsafe HTML characters在以 HTML 格式呈现 JSON 时,可能不安全的字符串 "</script>"变成 "\\u003c/script\\u003e"这是安全的。

关于python - 为什么 Flask 在其 json 模块中检查 `'\\/' in json.dumps('/')`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31883132/

相关文章:

python - 在 Pandas 数据框中随机插入 NA 的值 - 没有行完全丢失

python - Django View 没有返回值的函数

python - 使用 AsyncIOMainLoop 测试 Tornado 应用程序时出现 AssertionError "assert not IOLoop.initialized()"

python - 导入包时会发生什么?

python - Jinja2 遍历字典项列表

Linux Mint 上的 Python3 错误 "no module named bluetooth"

python - 不显示存储在运行 flask 文件的模板文件夹中的 gif 图像

python - Docker 图像中的 nginx 缓冲 flask 事件流

python - 在 Python Flask 中,如何在取消转义之前访问完整的原始 URL

python - 使用 Python,获取 zip 存档中的文件名