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

相关推荐
vx_bisheyuange9 分钟前
基于SpringBoot的老年一站式服务平台
java·spring boot·后端·毕业设计
大连好光景21 分钟前
批量匿名数据重识别(debug记录)
开发语言·python
暴风鱼划水26 分钟前
算法题(Python)哈希表 | 2.两个数组的交集
python·算法·哈希表
清水白石00828 分钟前
《深入 Celery:用 Python 构建高可用任务队列的实战指南》
开发语言·python
Tony Bai32 分钟前
Jepsen 报告震动 Go 社区:NATS JetStream 会丢失已确认写入
开发语言·后端·golang
bing.shao38 分钟前
Golang 之 defer 延迟函数
开发语言·后端·golang
BoBoZz191 小时前
Hello 隐式建模
python·vtk·图形渲染·图形处理
副露のmagic1 小时前
更弱智的算法学习day 10
python·学习·算法
penngo1 小时前
Golang使用Fyne开发桌面应用
开发语言·后端·golang
程序员清风1 小时前
别卷模型了!上下文工程才是大模型应用的王道!
java·后端·面试