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

相关推荐
kfaino1 小时前
码农的AI翻身(五)你好,我叫 Transformer
后端·aigc
Oneslide6 小时前
机械革命 单系统纯净重装Ubuntu(全盘覆盖,清空原有Windows)
后端
GetcharZp7 小时前
告别OOM!用Go+libvips实现30000×50000超大图片的流式瓦片服务
后端·go
IT_陈寒7 小时前
JavaScript项目实战经验分享
前端·人工智能·后端
用户47949283569158 小时前
6w star,GitHub 趋势第一的 Ponytail,这个agent插件到底在火什么
前端·后端
神奇小汤圆9 小时前
2026一线大厂Java八股文精选(附答案,高质量整理)
后端
Warson_L9 小时前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅9 小时前
海天线算法的前世今生
python·计算机视觉
韩师傅9 小时前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L9 小时前
LangGraph的MessageState and HumanMessage
python