环境准备
python安装:默认安装;
flask安装
pip install flask
api接口开发
get请求
from flask import Flask, request
import json
app = Flask(__name__)
# get请求
@app.route("/get", methods=["GET"])
def get():
# 默认返回内容
return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False}
# 判断入参是否为空
if request.args is None:
return_dict['return_code'] = '5004'
return_dict['return_info'] = '请求参数为空'
return json.dumps(return_dict, ensure_ascii=False)
# 获取传入的params参数
get_data = request.args.to_dict()
name = get_data.get('name')
age = get_data.get('age')
# 对参数进行操作
return_dict['result'] = tt(name, age)
return json.dumps(return_dict, ensure_ascii=False)
# 功能函数
def tt(name, age):
result_str = "%s今年%s岁" % (name, age)
return result_str
if __name__ == "__main__":
app.run(debug=True)
测试:使用postman调用接口
post请求
from flask import Flask, request
import json
app = Flask(__name__)
# post请求
@app.route("/post", methods=["POST"])
def post():
# 默认返回内容
return_dict = {'return_code': '200', 'return_info': '处理成功', 'result': False}
# 判断入参是否为空
if request.args is None:
return_dict['return_code'] = '5004'
return_dict['return_info'] = '请求参数为空'
return json.dumps(return_dict, ensure_ascii=False)
# 获取传入的参数
data = request.get_data()
data = json.loads(data)
name = data.get('name')
age = data.get('age')
# 对参数进行操作
return_dict['result'] = tt(name, age)
return json.dumps(return_dict, ensure_ascii=False)
# 功能函数
def tt(name, age):
result_str = "%s今年%s岁" % (name, age)
return result_str
if __name__ == "__main__":
app.run(debug=True)
测试:使用postman调用接口