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

相关推荐
弈栈录4 分钟前
MySQL 事务、索引与锁:后端开发必须掌握的数据库基础
数据库·后端
明月_清风5 分钟前
AI Agent 最大的问题,可能不是智商,而是“权限”
人工智能·后端
vx_Biye_Design8 分钟前
expressDeepSeek社团咨询助手的学生社团管理系统60746-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·课程设计·express
长安米粒贵9 分钟前
缓存明明加了,为什么数据还是不一致?聊聊 4 个容易忽略的边界
后端
yunwei3712 分钟前
eBPF 开发实践:使用 eBPF 隐藏进程或文件信息
linux·后端·性能优化
高频因子挖掘机14 分钟前
行情监控脚本重启后,怎样快速恢复而不重复拉取数据?
后端·github·api
aleafboat16 分钟前
只管去写(day2) 用claude分析老项目技术栈
后端
vx_Biye_Design22 分钟前
springboot宠物领养与救助平台64334-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·mysql·课程设计·宠物
用户77139702070624 分钟前
.NET 依赖注入入门
后端
泡茶喝茶写代码24 分钟前
A股量化数据工程:从 REST 接口到策略信号(第 5 篇):板块成分股映射与对齐
java·python·股票数据api·股票数据·股票数据api接口·股票api数据接口·股票量化数据接口