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

相关推荐
考虑考虑10 分钟前
Mybatis实现批量插入
java·后端·mybatis
咖啡八杯1 小时前
GoF设计模式——中介者模式
java·后端·spring·设计模式
金銀銅鐵2 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
lizhongxuan3 小时前
多Agent之间的区别
后端
Lyn_Li4 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
杨充5 小时前
1.面向对象设计思想
后端
IT_陈寒5 小时前
Java的Date类又坑了我一次,改用时间戳真香
前端·人工智能·后端
systemPro6 小时前
2.6亿条设备数据,历史查询从超时到50ms,我做了什么
后端
要阿尔卑斯吗6 小时前
提示词优化启示:为什么“按顺序输出“比“关键度评分“更有效
后端
她的男孩7 小时前
后台接口加密别只会 HTTPS,ForgeAdmin 的 RSA + SM4/AES 源码拆解
后端·面试·开源