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

相关推荐
BingoGo6 小时前
PHP clone 之后,为什么改副本会影响原对象?
后端·php
JaguarJack6 小时前
PHP clone 之后,为什么改副本会影响原对象?
后端·php·服务端
智能体与具身智能6 小时前
TVA具身智能的概念、架构与应用(19)
人工智能·python·具身智能
小灰灰搞电子6 小时前
Rust+Slint 实现动态消息提示框源码分享
开发语言·后端·rust
小奏技术7 小时前
10 MB 的 Postman 替代品,启动不到 1 秒
后端
东风破_7 小时前
Text2SQL :用自然语言操作 SQLite 数据库
人工智能·后端
2601_962294617 小时前
python中range函数怎么用
python·for循环·可迭代对象·range函数·整数列表
青 春 记 忆8 小时前
零基础入门python70:Docker Compose 编排完整后端
python·后端开发
新时代牛马8 小时前
字符设备驱动完整篇:从 cdev_add、file_operations 到chrdev_open 与排障
开发语言·python
白山编程大哥9 小时前
Java OutputStreamWriter 详解:从字符到字节的桥梁
java·开发语言·python