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

相关推荐
BBB努力学习程序设计几秒前
Python函数式编程:优雅的代码艺术
python·pycharm
2501_940943915 分钟前
体系课\ Python Web全栈工程师
开发语言·前端·python
q***06476 分钟前
SpringSecurity相关jar包的介绍
android·前端·后端
田姐姐tmner36 分钟前
Python切片
开发语言·python
陈橘又青1 小时前
100% AI 写的开源项目三周多已获得 800 star 了
人工智能·后端·ai·restful·数据
t***31651 小时前
爬虫学习案例3
爬虫·python·学习
2501_941148611 小时前
C++实时数据处理实战:多线程与异步IO结合高性能代码解析
java·后端·struts
IT_陈寒2 小时前
Redis实战:5个高频应用场景下的性能优化技巧,让你的QPS提升50%
前端·人工智能·后端
AI小云2 小时前
【数据操作与可视化】Pandas数据处理-其他操作
python·pandas
mzlogin2 小时前
借助 Let's Encrypt 节省 SSL 证书费用
后端·devops