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

相关推荐
Rain的Java大神之路11 分钟前
MySQL 与 Redis 双写一致性:从 Cache-Aside 到 Binlog 兜底,一次讲透
java·后端·面试
夜雪轻寒18 分钟前
Spring Boot 4 升级 Redis 序列化:编译报 tools.jackson.databind 不存在
spring boot·redis·后端
用户2986985301420 分钟前
Python 自动化处理 Word:按规则查找并高亮关键文本
python·api·编程语言
前端呆头鹅1 小时前
Node.js 作为单线程语言,是怎样处理高并发的?
后端·node.js
人工智能技术咨询.1 小时前
什么才算高质量数据集
python
DanCheng-studio2 小时前
毕业设计项目 机器视觉指纹识别特征对比算法(源码+论文)
python·毕业设计·毕设
梅雅达编程笔记2 小时前
一份 PDF 到底该拆成什么存进去:RAG 智能问答毕设数据库设计完整教程
python·flask·智能问答·毕设·向量数据库·rag·数据库设计
AI创界者2 小时前
Python 进阶实战(第八十三章):基于 Redis Lua 脚本的分布式令牌桶限流、异步熔断器状态机与信号优雅关机实战
人工智能·python·aigc
ZhengEnCi2 小时前
所有账号存一张表,权限怎么做隔离:从RBAC表结构到行级隔离的落地写法
数据库·后端·postgresql
码事漫谈11 小时前
AI 提效的真相:省下你的时间,填满你的硬盘
后端