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

相关推荐
幽络源小助理1 小时前
SpringBoot兼职发布平台源码 | JavaWeb项目免费下载 – 幽络源
java·spring boot·后端
写代码的【黑咖啡】1 小时前
Python中的Pandas:数据分析的利器
python·数据分析·pandas
co松柏1 小时前
AI+Excalidraw,用自然语言画手绘风格技术图
前端·人工智能·后端
机器懒得学习1 小时前
WGAN-GP RVE 生成系统深度技术分析
python·深度学习·计算机视觉
晨光32111 小时前
Day43 训练和测试的规范写法
python·深度学习·机器学习
海棠AI实验室1 小时前
Python 学习路线图:从 0 到 1 的最短闭环
开发语言·python·学习
玄同7651 小时前
Python 函数:LLM 通用逻辑的封装与复用
开发语言·人工智能·python·深度学习·语言模型·自然语言处理
踏浪无痕1 小时前
四个指标,一种哲学:Prometheus 如何用简单模型看透复杂系统
后端·架构·go
俞凡1 小时前
深入理解 Python GIL
python
luoluoal1 小时前
基于python的自然语言处理技术的话题文本分类的研究(源码+文档)
python·mysql·django·毕业设计·源码