Hello,
今天这里分享一些简单的API Mock 方法,测试小伙伴可以码住哦~
使用到的技术是Python , 三方库Flask。
一、
请看下方代码:
# !/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
from flask import Flask, request, jsonify
from Log import logger
app = Flask(__name__)
root_path = os.path.dirname(os.path.abspath(__file__))
@app.route('/')
def hello_world():
return 'Hello Mock Api'
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
这段代码随机运行我们即可在本地打开网址:127.0.0.1:5000
结果请看:
二、
请看下方代码:
# !/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
from flask import Flask, request, jsonify
from Log import logger
app = Flask(__name__)
root_path = os.path.dirname(os.path.abspath(__file__))
@app.route('/')
def hello_world():
return 'Hello Mock Api'
# get 路径参数
@app.route("/mock/print/<string:account>", methods=["GET"])
def print_req_para(account): # 参数名
return jsonify({"code": 200, "message": account})
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
这段代码随机运行我们即可在本地打开网址:127.0.0.1:5000/mock/print/(这里随便填一些内容即可)
结果请看:
三、
post请求
请看下方代码:
# !/usr/bin/python
# -*- coding: utf-8 -*-
import json
import os
from flask import Flask, request, jsonify
from Log import logger
app = Flask(__name__)
root_path = os.path.dirname(os.path.abspath(__file__))
@app.route('/')
def hello_world():
return 'Hello Mock Api'
# get 路径参数
@app.route("/mock/print/<string:account>", methods=["GET"])
def print_req_para(account): # 参数名
return jsonify({"code": 200, "message": account})
# post 请求
@app.route('/demo1/api', methods=["POST"])
def company_consolidated():
req = json.loads(request.get_data())
logger.info(req)
with open(os.path.join(root_path, r'mock_response\demo1.json'), 'r', encoding='utf-8') as res_json:
res_dict = json.load(res_json)
return jsonify(res_dict)
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
需要在项目路径下准备好post的响应内容文件
{
"Code": 1,
"Result": "Success",
"ErrorMessage": ""
}
谢谢~