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

相关推荐
Zhansiqi8 分钟前
dayy43
pytorch·python·深度学习
云原生指北10 分钟前
Omnipub E2E 测试文章 - 自动化验证
后端
IT_陈寒25 分钟前
SpringBoot自动配置揭秘:5个让开发效率翻倍的隐藏技巧
前端·人工智能·后端
紫丁香32 分钟前
pytest_自动化测试3
开发语言·python·功能测试·单元测试·集成测试·pytest
杰杰79835 分钟前
Python面向对象——类的魔法方法
开发语言·python
添尹1 小时前
Go语言基础之数组
后端·golang
chushiyunen1 小时前
python中的魔术方法(双下划线)
前端·javascript·python
深蓝轨迹1 小时前
@Autowired与@Resource:Spring依赖注入注解核心差异剖析
java·python·spring·注解
人工智能AI技术1 小时前
Python 3.14.3更新!内存优化与安全补丁实战应用
python
2401_891655811 小时前
此电脑网络位置异常的AD域排错指南的技术文章大纲
开发语言·python·算法