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

相关推荐
guchen661 分钟前
记录一次Prism9隐式注册引发的事件聚合器失效问题
后端
一行•坚书12 分钟前
kafka服务端与客户端如何协作?生产者发送消息分区策略是什么?消费者组分区策略?集群与ACK机制?
java·后端·kafka
Candice_jy15 分钟前
vscode运行ipynb文件:使用docker中的虚拟环境
服务器·ide·vscode·python·docker·容器·编辑器
天天摸鱼的java工程师28 分钟前
干掉系统卡顿!Excel异步导出完整实战方案(百万数据也不慌)
java·后端
星释34 分钟前
Rust 练习册 4:Deref trait 与智能指针
开发语言·后端·rust
Cache技术分享35 分钟前
231. Java 集合 - 将集合元素转换为数组
前端·后端
流烟默39 分钟前
基于Optuna 贝叶斯优化的自动化XGBoost 超参数调优器
人工智能·python·机器学习·超参数优化
海琴烟Sunshine41 分钟前
leetcode 263. 丑数 python
python·算法·leetcode
小码编匠1 小时前
WPF 绘制图表合集-LiveCharts
后端·c#·.net
codervibe1 小时前
MySQL 命令行连接与企业级远程访问实践(含故障排查与安全策略)
数据库·后端