Flask对请求进行多个格式的响应

Python:

python 复制代码
from flask import Blueprint, request, make_response, jsonify

index_page = Blueprint("index_page", __name__)


@index_page.route("/")
def hello():
    return "I Love jarvisyqliu"


@index_page.route("/my/<username>")
def my(username):
    return "I Love test %s" % username


@index_page.route("/get")
def get():
    req = request.values
    var_a = req['a'] if "a" in req else None
    return "request:%s,params:%s,var_a:%s" % (request.method, request.args, var_a)


@index_page.route("/post", methods=["POST"])
def post():
    req = request.values
    var_a = req['a'] if "a" in req else None
    return "request:%s,params:%s,var_a:%s" % (request.method, request.form, var_a)


@index_page.route("/upload", methods=["POST"])
def upload():
    f = request.files['file'] if "file" in request.files else None
    return "request:%s,params:%s,file:%s" % (request.method, request.files, f)


@index_page.route("/text")
def text():
    return "text/html"


@index_page.route("/text_same")
def text_same():
    response = make_response("text/html", 200)
    return response


@index_page.route("/json")
def json():
    import json
    data = {"a": "b"}
    response = make_response(json.dumps(data))
    response.headers["Content-Type"] = "application/json"
    return response


@index_page.route("/json_same")
def json_same():
    data = {"a": "b"}
    response = make_response(jsonify(data))
    return response


@index_page.route("/template")
def template():
    return render_template("index.html")

PS:jsonify会自动构建Content-Type为application/json

相关推荐
源代码•宸几秒前
GoLang并发简单例子(goroutine + channel + WaitGroup)
开发语言·经验分享·后端·学习·golang
将心ONE1 分钟前
pip导出项目依赖
开发语言·python·pip
稚辉君.MCA_P8_Java2 分钟前
Gemini永久会员 Go 返回最长有效子串长度
数据结构·后端·算法·golang
李少兄7 分钟前
解决 Spring Boot 中 YAML 配置文件的 `ArrayIndexOutOfBoundsException: -1` 异常
java·spring boot·后端
shx666611 分钟前
2.2.1 ROS2 在功能包中编写 Python 节点
开发语言·python·ros2
beijingliushao13 分钟前
100-Spark Local模式部署
大数据·python·ajax·spark
BoBoZz1916 分钟前
TessellatedBoxSource 创建并渲染一个细分的、可移动的箱体模型
python·vtk·图形渲染·图形处理
weixin_4573402127 分钟前
旋转OBB数据集标注查看器
图像处理·人工智能·python·yolo·目标检测·数据集·旋转
大猫子的技术日记31 分钟前
[后端杂货铺]深入理解分布式事务与锁:从隔离级别到传播行为
分布式·后端·事务
nvd1136 分钟前
LLM 对话记忆功能实现深度解析
python