Python Flask 开发:在 Flask 中返回字符串时,浏览器将其作为 HTML 解析

python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    return f'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 实体编码
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    type_str = str(type(username))
    type_str_escaped = type_str.replace('<', '&lt;').replace('>', '&gt;')
    return f'type: string, value: {username}, python_type: {type_str_escaped}'
  1. 使用 escape 函数
python 复制代码
from markupsafe import escape
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    type_str = str(type(username))
    return f'type: string, value: {username}, python_type: {escape(type_str)}'
  1. 使用 Markup 类
python 复制代码
from markupsafe import Markup
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    type_str = str(type(username))
    return f'type: string, value: {username}, python_type: {Markup.escape(type_str)}'
  1. 设置 content-type 为纯文本
python 复制代码
from flask import Flask, Response
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    content = f'type: string, value: {username}, python_type: {str(type(username))}'
    return Response(content, content_type='text/plain')
  1. 避免使用 HTML 特殊字符
python 复制代码
@app.route('/user/<string:username>')
def show_string(username):
    return f'type: string, value: {username}, python_type: {type(username).__name__}'
相关推荐
CodeSheep程序羊5 分钟前
拼多多春节加班工资曝光,没几个敢给这个数的。
java·c语言·开发语言·c++·python·程序人生·职场和发展
独好紫罗兰6 分钟前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
机器学习之心HML8 分钟前
多光伏电站功率预测新思路:当GCN遇见LSTM,解锁时空预测密码,python代码
人工智能·python·lstm
2401_8414956410 分钟前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
王大傻092813 分钟前
python 读取文件可以使用open函数的 r 模式
python
I'mChloe14 分钟前
PTO-ISA 深度解析:PyPTO 范式生成的底层指令集与 NPU 算子执行的硬件映射
c语言·开发语言
JarryStudy14 分钟前
HCCL与PyTorch集成 hccl_comm.cpp DDP后端注册全流程
人工智能·pytorch·python·cann
程序员良许19 分钟前
三极管推挽输出电路分析
后端·嵌入式
神梦流23 分钟前
GE 引擎的非标准数据流处理:稀疏张量与自定义算子在图优化中的语义保持
linux·运维·服务器
Java水解25 分钟前
【JAVA 进阶】Spring AOP核心原理:JDK与CGLib动态代理实战解析
后端·spring