标签:desc 准备 python 通过 ack 接口调用 简单 call mes
Python+Flask搭建mock api server
近期由于工作需要,需要一个Mock Server调用接口直接返回API结果;
假如可以先通过接口文档的定义,自己模拟出服务器返回结果,直接对接口基本功能进行联调测试并编写自动化测试脚本,等服务器上线之后,切换server地址,直接可以简化调试时间,缩短项目测试周期;
Python安装
Flask安装:pip install flask
from flask import abort, jsonify, Flask, request, Response app = Flask(__name__) tasks = { "data": { "loginName": "admin", "roles": 1, "permissions": 1, "active": 1 }, "stateCode": { "code": 0, "desc": "成功" }, "statusText": "成功", "timestamp": "1500531770453", "success": 1 } @app.route("/task", methods=[‘GET‘]) def get_all_task(): return jsonify(tasks) if __name__ == "__main__": if __name__ == "__main__": app.run( host = "127.0.0.1", port = 8989, debug = True )
python test.py (
test.py为上述代码保存文件名)
http://127.0.0.1:8989/task
Post方式由于需要传递参数,并且有多种不同类型,比如json比如表单等,本文就不细说只是一篇入门;
from flask import abort, jsonify, Flask, request, Response app = Flask(__name__) tasks = { "data": { "loginName": "admin", "roles": 1, "permissions": 1, "active": 1 }, "stateCode": { "code": 0, "desc": "成功" }, "statusText": "成功", "timestamp": "1500531770453", "success": 1 } @app.route(‘/v1/testMock‘, methods=[‘GET‘, ‘POST‘]) def app_call_back(): if request.method == ‘GET‘: return jsonify(tasks) else: test_data = request.form[‘params‘] return jsonify(test_data) if __name__ == "__main__": app.run( host = "127.0.0.1", port = 8989, debug = True )
http://127.0.0.1:8989/v1/testMock?params=test_mock
默认Flask调用jsonify返回结果是utf8,如果需要返回支持中文显示,只需要在app = Flask(name)下增加一行:
app.config[‘JSON_AS_ASCII‘] = False
标签:desc 准备 python 通过 ack 接口调用 简单 call mes
原文地址:https://www.cnblogs.com/ai594ai/p/10783117.html