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

相关推荐
掘金者阿豪2 分钟前
数据库性能优化:一次慢查询背后,可能不只是SQL的问题
前端·后端
AskHarries42 分钟前
联盟营销怎么玩
后端
承渊政道2 小时前
【Python编程—从入门到实践】(用户账户:给Django网站装上登录系统,让每个人拥有自己的学习笔记)
python·学习·pycharm·django
一条Go2 小时前
Webhook 签名:钉钉、企业微信、飞书的四种算法差异
后端·架构·github
不一样的少年_2 小时前
用了这 Skill,我觉得前端兄弟可以毕业了
前端·后端·agent
梦想很大很大3 小时前
一句“你好”用了 5671 Token:我在 Workrun 中追查 Agent 隐性成本的过程
前端·人工智能·后端
坤岭3 小时前
Agentic BI 落地实战
后端
SimonKing3 小时前
AI Assistant被"隐藏"了?别慌,IDEA 2026.3 这波是换了个脑子
java·后端·程序员
核桃er3 小时前
RuoYi-Vue 源码中的 Spring IoC 与 DI(两个实例)
后端
小番茄程序猿3 小时前
一条 ALTER 拖死全表:MDL 阻塞的完整时间线(8.4.11 实测)
后端·mysql