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

相关推荐
2301_7950997418 分钟前
如何优化SQL中大批量数据的物理删除_分批次与间隔控制
jvm·数据库·python
阿kun要赚马内21 分钟前
后端数据操作组合:Pydantic与ORM
后端·python·orm·sqlalchemy
2301_8125396727 分钟前
CSS如何引入CSS形状生成器_通过自定义属性实现图形化样式
jvm·数据库·python
m0_609160491 小时前
Golang怎么实现数据库连接重试_Golang如何在启动时重试连接直到数据库就绪【技巧】
jvm·数据库·python
花米徐1 小时前
技术洞察精选 | 2026年4月28日 — 5月4日
后端·python·flask
阿维的博客日记2 小时前
Spring Cloud 为什么需要服务注册与发现中心这些东西?
后端·spring·spring cloud
笑而不语2 小时前
13|元数据过滤检索:UserContext 与按用户查知识
后端
宝贝儿好2 小时前
【LLM】第三章:项目实操案例:智能输入法项目
人工智能·python·深度学习·算法·机器人
m0_624578592 小时前
如何在phpMyAdmin中导入GZIP压缩格式文件_加速传输并突破文件大小限制
jvm·数据库·python
m0_495496412 小时前
mysql数据库表名区分大小写吗_通过lower case table names配置
jvm·数据库·python