Python Flask 开发:在 Flask 中返回字符串时,浏览器将其作为 HTML 解析
2026/5/16 20:36:17 网站建设 项目流程
@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'>
问题原因
  1. 当在 Flask 中返回字符串时,浏览器将其作为 HTML 解析

  2. <class 'str'>中的字符<>在 HTML 中有特殊含义,即标签的界定符

处理策略
  1. 使用 HTML 实体编码
@app.route('/user/<string:username>')defshow_string(username):type_str=str(type(username))type_str_escaped=type_str.replace('<','&lt;').replace('>','&gt;')returnf'type: string, value:{username}, python_type:{type_str_escaped}'
  1. 使用 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)}'
  1. 使用 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)}'
  1. 设置 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')
  1. 避免使用 HTML 特殊字符
@app.route('/user/<string:username>')defshow_string(username):returnf'type: string, value:{username}, python_type:{type(username).__name__}'

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询