在前后端分离的项目中,
前端无需等后端接口提供了才调试,
后端无需等第三方接口提供了才调试,
基于“契约”,可以通过mock server实现调试,
下面是一个简单的mock server,通过python的Flask框架实现,
mock_test.py
from flask import Flask, jsonify, g
import copy
app = Flask(__name__) @app.before_request
def set_up_data():
g.data = [
{'id': 1, 'uname': 'tom'},
{'id': 2, 'uname': 'jcck'},
{'id': 3, 'uname': 'lucy'}
] g.user_does_not_exist = {"msg": "user does not exist"} @app.route('/api/user')
def get_all_users():
return jsonify(g.data) @app.route('/api/user/<int:user_id>')
def get_user(user_id):
if user_id > 0 and user_id <= len(g.data):
return jsonify(g.data[user_id-1])
else:
return jsonify(g.user_does_not_exist)
# set FLASK_APP=mock_test.py
# flask run
获取所有用户:
http://localhost:5000/api/user
获取指定用户:
http://localhost:5000/api/user/2
非法字符:
http://localhost:5000/api/user/a
改进mock_test.py
from flask import Flask, jsonify, g
import copy
app = Flask(__name__) @app.before_request
def set_up_data():
g.data = [
{'id': 1, 'uname': 'tom'},
{'id': 2, 'uname': 'jack'},
{'id': 3, 'uname': 'lucy'}
] g.user_does_not_exist = {"code":"01", "msg": "user does not exist"} @app.route('/api/user')
def get_all_users():
print(type(jsonify(g.data)))
# return jsonify(g.data)
return jsonify({"code":"00", "msg":g.data}) @app.route('/api/user/<int:user_id>')
def get_user(user_id):
if user_id > 0 and user_id <= len(g.data):
# return jsonify(g.data[user_id-1])
return jsonify({"code":"00","msg":g.data[user_id-1]})
else:
return jsonify(g.user_does_not_exist) # set FLASK_APP=mock_test.py
# flask run