Python+Flask搭建mock api server

2017-08-28  本文已影响0人  骨头骨头懒骨头

Python+Flask搭建mock api server

前言:

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

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

准备工作

Python安装

Flask安装:pip install flask

Get 请求

简单的python代码

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

Curl接口调用测试:

curl -i "http://127.0.0.1:8989/task"

Post请求

Post方式由于需要传递参数,并且有多种不同类型,比如json比如表单等,本文就不细说只是一篇入门;

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
        )

Curl接口调用测试:

curl -d "params=test_mock" "http://127.0.0.1:8989/v1/testMock

Flask让jsonify返回的json串支持中文显示:

默认Flask调用jsonify返回结果是utf8,如果需要返回支持中文显示,只需要在app = Flask(name)下增加一行:

app.config['JSON_AS_ASCII'] = False

参考资料:

https://stackoverflow.com/questions/37531067/how-to-prevent-unicode-representation-for-latin1-characters

http://flask.pocoo.org/

上一篇下一篇

猜你喜欢

热点阅读