日常开发/测试过程中,需要对相关服务添加挡板--Mock
简单介绍一下使用python的Flask插件,对相关的服务进行Mock
# coding:utf-8 import os from flask import Flask, render_template, request app = Flask(__name__, static_folder=".", template_folder="./templates") @app.route('/delete') def index(): return render_template('index.html') @app.route('/delete/user', methods=['GET', 'POST']) def delete(): get_data = request.values.get('c_id') get_id = request.values.get('id') if len(get_data) == 0 or len(get_id) == 0: return render_template('index.html', data="Please check your custom id or id.") p = os.popen("sh /home/xx.sh " + get_data + " " + get_id).read() if len(p) == 0: return render_template('index.html', data="Execute False. custom_id=" + get_data + " id=" + get_id) else: return render_template('index.html', data=str(p)+" custom_id=" + get_data + " id=" + get_id) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=80)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>删除用户</title> </head> <body> <br></br> <br></br><br></br> <div style='color:blue;text-align:center'> <form method="post" action="/delete/user"> <input maxlength="12" type="text" name="c_id" id="c_id" placeholder="input custom id" value=""style="font-size:1.4em;height:2.7em;border-radius:10px;border:1px solid #c8cccf;color:#986655;"> <input maxlength="18" type="text" name="id" id="id" placeholder="input id" value="" style="font-size:1.4em;height:2.7em;border-radius:10px;border:1px solid #c8cccf;color:#986655;"> <input type="submit" value=" Delete " style="font-size:1.4em;height:2.7em;border-radius:10px;border:1px solid #c8cccf;color:#986655;"/> </form> <br><br><br> {% if data %} <span>{{data}}</span> {% endif %} </div> </body> </html>
以上的代码,只是通过页面的元素来获取对应的值,然后通过值作为参数,进行执行
再介绍一个使用json发送接口的使用方式。具体需要修改的地方,要根据实际情况来进行。
# coding:utf-8 import random from flask import Flask, request, jsonify, abort app = Flask(__name__) # 实例化一个Flask对象 @app.route("/api/user/reg/", methods=["POST"]) def reg(): if not request.json or 'name' not in request.json or 'password' not in request.json: code = {"code": "404", "msg": "失败", "data": {}} return jsonify(code) # abort(404) res = [ { "code": "100000", "msg": "成功", "data": { "name": "李六", "password": "e10adc3949ba59abbe56e057f20f883e" } }, { "code": "100001", "msg": "失败,用户已存在", "data": { "name": "李六", "password": "e10adc3949ba59abbe56e057f20f883e" } }, { "code": "100002", "msg": "失败,添加用户失败", "data": { "name": "李六", "password": "e10adc3949ba59abbe56e057f20f883e" } } ] return jsonify(random.choice(res)) if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)
---------我是底线---------