@app.route('/user/<string:username>')defshow_string(username):returnf'type: string, value:{username}, python_type:{str(type(username))}'- 在 Python Flask 开发中,访问上述接口
/user/john_doe时,在浏览器中,会输出以下结果
type: string, value: john_doe, python_type:- 但是,在控制台中,会输出以下结果
type: string, value: john_doe, python_type: <class 'str'>问题原因
当在 Flask 中返回字符串时,浏览器将其作为 HTML 解析
<class 'str'>中的字符<与>在 HTML 中有特殊含义,即标签的界定符
处理策略
- 使用 HTML 实体编码
@app.route('/user/<string:username>')defshow_string(username):type_str=str(type(username))type_str_escaped=type_str.replace('<','<').replace('>','>')returnf'type: string, value:{username}, python_type:{type_str_escaped}'- 使用 escape 函数
frommarkupsafeimportescape@app.route('/user/<string:username>')defshow_string(username):type_str=str(type(username))returnf'type: string, value:{username}, python_type:{escape(type_str)}'- 使用 Markup 类
frommarkupsafeimportMarkup@app.route('/user/<string:username>')defshow_string(username):type_str=str(type(username))returnf'type: string, value:{username}, python_type:{Markup.escape(type_str)}'- 设置 content-type 为纯文本
fromflaskimportFlask,Response@app.route('/user/<string:username>')defshow_string(username):content=f'type: string, value:{username}, python_type:{str(type(username))}'returnResponse(content,content_type='text/plain')- 避免使用 HTML 特殊字符
@app.route('/user/<string:username>')defshow_string(username):returnf'type: string, value:{username}, python_type:{type(username).__name__}'