Python:Flask请求参数和响应探究

一、参数传递

测试代码

# -*- coding: utf-8 -*-

from flask import Flask, request

app = Flask(__name__)


@app.route("/", methods=['POST', 'GET'])
def index():
    print(request.args)
    print(request.form)
    print(request.values)
    print(request.data)
    print(request.json)
    return "ok"


if __name__ == '__main__':
    app.run(debug=True)

请求测试

1、发送json数据

POST http://127.0.0.1:5000/?age=12
Content-Type: application/json

{
"name": "Tom"
}

收到的数据如下

request.args   [('age', '12')]
request.form   []
request.values [('age', '12')]
request.data   b'{\n"name": "Tom"\n}'
request.json   {'name': 'Tom'}

2、发送form数据

POST http://127.0.0.1:5000/?age=12
Content-Type: application/x-www-form-urlencoded

name=Tom

收到的数据如下'

request.args  [('age', '12')]
request.form  [('name', 'Tom')]
request.values  [('age', '12'), ('name', 'Tom')]
request.data  b''
request.json  None

如果request.argsrequest.form 数据相同,会优先取request.args 中的数据

二、升级参数接收

通过测试发现,如果前端没有传递正确的json数据,request.json 会返回一个None ,如果直接取数据会报错,目前主流的传参方式是json数据,我们改装一下:

# -*- coding: utf-8 -*-

from flask import Flask, request, Request


class MyRequest(Request):

    @property
    def json(self):
        """避免json数据未传递而返回 None"""
        try:
            data = self.get_json()
        except Exception as e:
            data = None

        return data or {}

    @property
    def params(self):
        """
        将参数全都放入一个变量
        参数获取顺序 args > form > json
        :return: {dict}
        """
        data = {}

        for key, value in self.args.items():
            data.setdefault(key, value)

        for key, value in self.form.items():
            data.setdefault(key, value)

        for key, value in self.json.items():
            data.setdefault(key, value)

        return data


app = Flask(__name__)
app.request_class = MyRequest


@app.route("/", methods=['POST', 'GET'])
def index():
    print(request.args)
    print(request.form)
    print(request.values)
    print(request.data)
    print(request.json)
    print(request.params)
    return request.params


if __name__ == '__main__':
    app.run(debug=True)

MyRequest 类 修改了 json 方法,捕获了异常,避免返回 None 报错,添加了params 方法,将所有参数都封装到里边,简化参数获取,不过不能准确获取参数

三、返回参数

视图函数不能直接返回 list 参数,所以改造一下

# -*- coding: utf-8 -*-

from flask import Flask, request, Request, jsonify


class MyRequest(Request):

    @property
    def json(self):
        """避免json数据未传递而返回 None"""
        try:
            data = self.get_json()
        except Exception as e:
            data = None

        return data or {}

    @property
    def params(self):
        """
        将参数全都放入一个变量
        处理参数顺序 args > form > json
        :return: {dict}
        """
        data = {}

        for key, value in self.args.items():
            data.setdefault(key, value)

        for key, value in self.form.items():
            data.setdefault(key, value)

        for key, value in self.json.items():
            data.setdefault(key, value)

        return data


class MyFlask(Flask):
    request_class = MyRequest

    def make_response(self, rv):
        """视图函数可以直接返回list 或者 dict"""
        if isinstance(rv, (list, dict)):
            return jsonify(rv)
        return super().make_response(rv)

    def post(self, rule, **options):
        """便于书写post方法"""
        options.setdefault('methods', ['POST'])
        return self.route(rule, **options)


app = MyFlask(__name__)


@app.post("/")
def index():
    return ['cat', 'pig']


if __name__ == '__main__':
    app.run(debug=True)

额外添加了post方法,便于书写post请求

相关文章

  1. Flask最佳实践-1
  2. Flask最佳实践-2
上一篇:TableStore时序数据存储 - 架构篇


下一篇:抗击疫情,阿里云数据库团队这样做…