Python+Flask搭建mock api server
前言:
近期由于工作需要,需要一个Mock Server调用接口直接返回API结果;
假如可以先通过接口文档的定义,自己模拟出服务器返回结果,直接对接口基本功能进行联调测试并编写自动化测试脚本,等服务器上线之后,切换server地址,直接可以简化调试时间,缩短项目测试周期;
准备工作
Python安装
Flask安装:pip install flask
准备代码
简单的python代码
# encoding: utf-8from flask import abort, jsonify, Flask, request, Response app = Flask(__name__)#定义域名,然后通过配置hosts的方式访问此域名下对应的接口app.config['SERVER_NAME']='test.wondershare.mock' tasks1 = { "data": { "loginName": "aaaaaa", "roles": 1, "permissions": 1, "active": 1 }, "stateCode": { "code": 1, "desc": "成功1" }, "statusText": "成功1", ", "success": 1 } tasks2 = { "data": { "loginName": "bbbbbb", "roles": 2, "permissions": 2, "active": 2 }, "stateCode": { "code": 2, "desc": "成功2" }, "statusText": "成功2", ", "success": 2 } error = { "data": {}, "stateCode": { "code": 500, "desc": "没有找到对应接口" }, "statusText": "没有找到对应接口", ", "success": 0 } #定义路由 @app.route('/v1/testMock', methods=['GET', 'POST']) def testMock(): try: if request.method == 'GET': #获取地址中test参数的值 test = request.args.get('test') ': return jsonify(tasks1) ': return jsonify(tasks2) else: test = request.form.get('test') ': return jsonify(tasks1) ': return jsonify(tasks2) except IOError: return("Error:报错了!!!") else: return jsonify(error) if __name__ == "__main__": app.run( host = "127.0.0.1", port = 80, debug = True )
启动服务:
python test.py
test.py为上述代码保存文件名
接口调用测试:
http://127.0.0.1/v1/testMock?test=1
Flask让jsonify返回的json串支持中文显示:
默认Flask调用jsonify返回结果是utf8,如果需要返回支持中文显示,只需要在app = Flask(name)下增加一行:
app.config['JSON_AS_ASCII'] = False