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

相关推荐
znhy_237 分钟前
day35打卡
python
何中应21 分钟前
【面试题-5】设计模式
java·开发语言·后端·设计模式·面试题
盼哥PyAI实验室21 分钟前
12306反反爬虫策略:Python网络请求优化实战
网络·爬虫·python
Kiri霧23 分钟前
Go包基础与使用指南
开发语言·后端·golang
重生之后端学习26 分钟前
56. 合并区间
java·数据结构·后端·算法·leetcode·职场和发展
deephub28 分钟前
DeepSeek-R1 与 OpenAI o3 的启示:Test-Time Compute 技术不再迷信参数堆叠
人工智能·python·深度学习·大语言模型
力江43 分钟前
FastAPI 最佳架构实践,从混乱到优雅的进化之路
python·缓存·架构·单元测试·fastapi·分页·企业
Raink老师1 小时前
第 11 章 错误处理与异常
python
Lululaurel1 小时前
AI编程文本挖掘提示词实战
人工智能·python·机器学习·ai·ai编程·提示词
HappRobot1 小时前
Python 面向对象
开发语言·python