Python+Flask搭建mock api server

Python+Flask搭建mock api server

前言:

近期由于工作需要,需要一个Mock Server调用接口直接返回API结果;

假如可以先通过接口文档的定义,自己模拟出服务器返回结果,直接对接口基本功能进行联调测试并编写自动化测试脚本,等服务器上线之后,切换server地址,直接可以简化调试时间,缩短项目测试周期;

准备工作

Python安装

Flask安装:pip install flask

准备代码

简单的python代码

from flask import abort, jsonify, Flask, request, Response

app = Flask(__name__)
#app.config['SERVER_NAME']='test.wondershare.mock'

tasks1 = {
    "data": {
        "loginName": "aaaaaa",
        "roles": 1,
        "permissions": 1,
        "active": 1
    }
    "statusText": "成功1",
    "timestamp": "1500531770453",
    "success": 1
}
tasks2 = {
    "data": {
        "loginName": "bbbbbb",
        "roles": 2,
        "permissions": 2,
        "active": 2
    }
    "statusText": "成功2",
    "timestamp": "1500531770453",
    "success": 2
}
error = {
    "data": {},
    "statusText": "没有找到对应接口",
    "timestamp": "1500531770453",
    "success": 0
}

#定义路由
@app.route('/v1/testMock', methods=['GET', 'POST'])
def testMock():
    try:
        if request.method == 'GET':    
            #获取地址中test参数的值
            test = request.args.get('test')
            if test == '1':
                return jsonify(tasks1)
            elif test == '2':
                return jsonify(tasks2)
            else:
                return jsonify(error)
        else:
            test = request.form.get('test')
            if test == '3':
                return jsonify(tasks1)
            elif test == '4':
                return jsonify(tasks2)
            else:
                return jsonify(error)
    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

 

 
 

你可能感兴趣的:(Python+Flask搭建mock api server)