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

相关推荐
普通网友10 小时前
pytest一些常见的插件
开发语言·python·pytest
时空系11 小时前
Python 高性能高压缩打包器 —— 基于 JianPy 语义分析引擎
python
饼干哥哥11 小时前
Vibe Coding 出海首月收割 100+用户爆赚美金,怎么做?
后端·架构·代码规范
cndes11 小时前
给Miniconda换源,让包下载更迅速
开发语言·python
大康11 小时前
macOS Homebrew 重装与国内镜像配置手册
后端
行者全栈架构师11 小时前
大模型批量生成代码的质量衰减:为什么 AI 越写越敷衍?根因分析与系统性解决方案
后端·架构·代码规范
乐观的Terry11 小时前
1、为什么要自己造发布系统
java·spring boot·后端·spring cloud·架构
用户EasyAdminBlazor11 小时前
EasyAdminBlazor 第十篇:数据导入导出——批量处理不再麻烦
前端·后端
Metaphor69211 小时前
使用 Python 添加、隐藏和删除 PDF 图层
python·pdf·图层
丨白色风车丨11 小时前
【Python 计算机视觉】基于 Dlib+OpenCV 实现实时人眼疲劳检测(闭眼预警)
python·opencv·计算机视觉