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

相关推荐
nimadan1210 分钟前
**AI漫剧软件2025推荐,解锁高性价比创意制作新体验**
人工智能·python
Java后端的Ai之路2 小时前
【JDK】-JDK 21 新特性内容
java·开发语言·后端·jdk·jdk21
yunhuibin3 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
易辰君3 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
普通网友3 小时前
PHP语言的正则表达式
开发语言·后端·golang
秀儿还能再秀4 小时前
正则表达式核心语法 + Python的 re 库中常用方法
python·正则表达式
xcLeigh4 小时前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
多恩Stone4 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python
葵续浅笑5 小时前
从Spring拦截器到Filter过滤器:一次报文修改加解密的填坑经验
java·后端·spring
XW01059995 小时前
4-11判断素数
前端·python·算法·素数