欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python Flask编写API接口

程序员文章站 2022-03-31 21:15:12
...

最近在用Pyhon写测试工具平台,编写一些工具来解决日常繁琐的问题以提高工作效能,会将过程中遇到的一些问题记录下来,尽量写的详细一些,仅供参考。大佬略过(狗头保命)。

在编写工具的过程中,无可避免的需要写一些后端接口供前端调用,以下为常见的几种获取接口入参的方法

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.route('/data', methods=['get', 'post'])
def get_data():
    # 获取URL中的参数,例:http://127.0.0.1:5000/data?page=1&limit=10,获取?后的数据
    print('URL中的参数:%s' % request.args)
    # 获取表单数据,即Content-Type为multipart/form-data的数据
    print('表单数据:%s' % request.form)
    # 获取Content-Type为application/json的数据
    print('application/json的数据:%s' % request.json)
    # 获取Content-Type为text/plain的数据
    print('text/plain的数据:%s' % request.data)
    # 获取请求头
    print('请求头:%s' % request.headers)
    # 获取请求路径
    print('请求路径:%s' % request.path)
    # 获取user_agent
    print('user_agent:%s' % request.user_agent)
    # 获取请求地址
    print('请求地址:%s' % request.url)
    # 获取Cookies
    print('Cookies:%s' % request.cookies)
    # 获取认证数据
    print('认证数据:%s' % request.authorization)
    # 获取上传文件
    print('上传文件:%s' % request.files)
    # jsonify可返回list, dict等格式的数据
    return jsonify(request.json)


if __name__ == '__main__':
    app.run(debug=False, host='0.0.0.0')

下面以POSTMAN调用为例

获取URL中的参数


Python Flask编写API接口
若想获取上图中的参数,可用request.args方法,结果如下

URL中的参数:ImmutableMultiDict([('page', '1'), ('limit', '10')])

ImmutableMultiDict类型可通过.get()方法获取其中的某一项值,如:request.args.get('page'),下同。

获取表单数据


Python Flask编写API接口
若想获取上图中的参数,可用request.form方法,结果如下

表单数据:ImmutableMultiDict([('page', '2'), ('limit', '20')])

获取application/json入参


Python Flask编写API接口
若想获取上图中的参数,可用request.json方法,结果如下

application/json的数据:{'page': 3, 'limit': 22}

获取text/plain入参

Python Flask编写API接口
若想获取上图中的参数,可用request.data方法,结果如下

text/plain的数据:b'{"page":3,"limit":22}'

获得的数据类型为bytes,可通过request.data.decode()方法将其转换为str类型

获取认证数据

Python Flask编写API接口
若想获取上图中的参数,可用request.authorization方法,结果如下

认证数据:{'username': 'admin', 'password': '123456'}

获取上传文件

Python Flask编写API接口
若想获取上图中的参数,可用request.files方法,结果如下

上传文件:ImmutableMultiDict([('upload', <FileStorage: 'test.png' ('image/png')>)])

可通过如下方式保存文件

file = request.files.get('upload')
# 文件名称
file_name = file.filename
# 保存图片
file.save(file_name)

其他

其他几个方法很简单,就不在这里赘述了。

最后讲一下flask.jsonify()方法,举个例子

from flask import Flask

app = Flask(__name__)


@app.route('/data', methods=['get', 'post'])
def get_data():
    return {"test": True}


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

调用该方法会抛出如下异常

Traceback (most recent call last):
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\_compat.py", line 35, in reraise
    raise value
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\app.py", line 1816, in full_dispatch_request
    return self.finalize_request(rv)
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\app.py", line 1831, in finalize_request
    response = self.make_response(rv)
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\app.py", line 1982, in make_response
    reraise(TypeError, new_error, sys.exc_info()[2])
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\_compat.py", line 34, in reraise
    raise value.with_traceback(tb)
  File "D:\Program Files\Python\Python37\lib\site-packages\flask\app.py", line 1974, in make_response
    rv = self.response_class.force_type(rv, request.environ)
  File "D:\Program Files\Python\Python37\lib\site-packages\werkzeug\wrappers.py", line 921, in force_type
    response = BaseResponse(*_run_wsgi_app(response, environ))
  File "D:\Program Files\Python\Python37\lib\site-packages\werkzeug\wrappers.py", line 59, in _run_wsgi_app
    return _run_wsgi_app(*args)
  File "D:\Program Files\Python\Python37\lib\site-packages\werkzeug\test.py", line 923, in run_wsgi_app
    app_rv = app(environ, start_response)
TypeError: 'dict' object is not callable
The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict.

可以看到,flask的返回默认只支持string, tuple, Response instance, WSGI callable。那么如果想返回listdict这些类型的数据,则需要用到flask.jsonify()方法

from flask import Flask, jsonify

app = Flask(__name__)


@app.route('/data', methods=['get', 'post'])
def get_data():
    return jsonify({"test": True})


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

结果如下
Python Flask编写API接口

未完待续

相关标签: Python Flask API