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

相关推荐
现任明教教主~14 分钟前
SpringBoot+Vue学生宿舍管理系统源码 带部署文档
vue.js·spring boot·后端
码事漫谈7 小时前
骂AI,会让它做得更好吗?
后端
“AI国潮设计-小江”7 小时前
《Python+SDXL实战:用ControlNet精准控制“英歌舞翻糖吐司”构图,附批量生成脚本》
开发语言·人工智能·python·prompt·aigc
wenwen_chao7 小时前
Python学习与开发资源合集:实用技巧与工具推荐
python
陈随易7 小时前
bm2,Node.js 与 Bun 项目部署新选择
前端·后端·程序员
for_ever_love__8 小时前
函数——参数、lambda、*args与作用域
python·函数·大模型开发·编程基础
东莞市云毅网络有限公司8 小时前
企业资料时效性判定:Last-Modified、正文日期与版本字段三路交叉
python·sqlite·自动化运维·geo·数据监测
Query*8 小时前
深入浅出LangGraph【一】_基础篇
python·ai·langchain
架构技术专栏9 小时前
AI Agent 框架怎么选:从一次制度查询拆出技术边界
后端·面试
XiaoMaqqqq9 小时前
市面上正规的IP驱动产业新场景新工具哪家强
运维·python·网络协议·tcp/ip