python flask API接口

以json形式传入数据

server.py

from flask import Flask, request
import json
 
app = Flask(__name__)
 
 
# 只接受POST方法访问
@app.route("/test_1",methods=["POST"])
def check():
    # 默认返回内容
    return_dict = {'statusCode': '200', 'message': 'successful!', 'result': False}
    # 判断入参是否为空
    if request.get_data() is None:
        return_dict['statusCode'] = '5004'
        return_dict['message'] = '请求参数为空'
        return json.dumps(return_dict, ensure_ascii=False)
 
    get_data = request.get_data()  # 获取传入的参数
    get_data = json.loads(get_data)  # 传入的参数为bytes类型,需要转化成json
    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)

 

test.py

# coding=utf-8
import json
import requests
import time
import sys
import os
# sys.path.append(os.getcwd())
print(sys.argv)
# os.chdir(sys.argv[0])
os.chdir(sys.path[0])
 
time_start = time.time()
if __name__ == '__main__':
    testData = {"name": "小明", "age": 18}
    response = requests.post('http://localhost:5000/test_1', json=testData)
 
print(response.text)
 
time_end = time.time()
print('totally cost', time_end-time_start)

 

result

{"statusCode": "200", "message": "successful!", "result": "小明今年18岁"}
totally cost 0.007977962493896484

 

postman测试

python flask API接口_第1张图片

 

参考文献:https://blog.csdn.net/t8116189520/article/details/86623320

你可能感兴趣的:(python学习)