用flask搭建一个测试数据生成器(v1.1)
在v1.0版本中实现了"页面点击按钮,生成对应测试数据"的功能,但是在操作页面只有一个按钮,没有提供任何参数(即没有涉及到参数在前后端传递,只是单纯的触发请求);
这次在前端页面给每个按钮加一个参数,用来控制生成测试数据的个数,更改后的页面大概如下
所以接下来要做如下改造工作:
- 改造html模版,在每个按钮后添加一个输入框(添加input标签);
- 改造视图函数,例如phone()函数,使它能够接收一个参数,控制生成数据的个数;
- 改造js代码,使它能够接收input标签输入的值;
一、修改 base.html 和 base.css
为每个按钮添加一个输入框,另外调整下整体布局,base.html 代码如下
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}" type="text/css"> 7 <script type="text/javascript" src="{{ url_for('static', filename='jquery-3.5.1.js') }}"></script> 8 </head> 9 <body> 10 <div class="left"> 11 <div class="b1"> 12 <form method="get" action=""> 13 <button type="button" id="b01">手机号码</button> 14 <label> 15 <input type="text" name="phone_num" id="pnone_num" value="" placeholder="请输入个数"> 16 </label> 17 </form> 18 19 </div> 20 21 <div class="b1"> 22 <form method="get" action=""> 23 <button type="button" id="b02">身份证ID</button> 24 <label> 25 <input type="text" name="card_id" id="id_num" value="" placeholder="请输入个数"> 26 </label> 27 </form> 28 </div> 29 30 <div class="b1"><button type="button" id="b03">人名</button> 31 <label> 32 <input type="text" name="name" value="" placeholder="请输入个数"> 33 </label> 34 </div> 35 <div class="b1"><button type="button" id="b04">一段文字</button></div> 36 <div class="b1"><button type="button" id="b05">特殊字符</button> 37 <label for=""><select name="special" id="select"> 38 <option value="5">5个</option> 39 <option value="10">10个</option> 40 <option value="20">20个</option> 41 </select></label> 42 </div> 43 44 <div class="b1"><button style="background-color:darkred;color: #fcfcfc" type="button" id="b07">清空输出</button></div> 45 </div> 46 47 <div ><label for="result"></label><textarea class="textera" name="" id="result" cols="103" rows="20"></textarea></div> 48 49 50 </body> 51 </html>
base.css代码如下
.b1 { /*float: left;*/ /*display: inline;*/ /*background-color: #7ED321;*/ margin-right: 20px; margin-left: 50px; margin-top: 20px; } div .left { float:left; color: #f00; border: 2px; } input .w { width: 1px; } .textera { position:absolute; left: 350px; top: 20px; background-color: #f1f1d1; }
二、改造视图函数
因为之前当触发按钮时,触发的get请求如下
http://127.0.0.1:5000/phone
现在要加一个参数,假设参数名为num,希望触发的get请求变为如下形式
http://127.0.0.1:5000/phone?num=
后台路由如果想接收这种形式的参数,例如上面的num,则可以通过下面这种方式
request.args.get("num")
以phone()视图函数为例,改造后如下
def create_phone(num): """生成电话""" phones = [fake.phone_number() for _ in range(int(num))] return " ".join(phones) @app.route('/phone', methods=['POST', 'GET']) def phone(): num = request.args.get("num") if num == "": # 如果接收到的num为空,则默认传5 data = create_phone(5) else: data = create_phone(num) return data
三、改造js代码,使它能够接收input标签输入的值
在实现过程中,一直在想如何从前端获取input标签输入的num参数值,传递给后端路由
经过多方查找资料,还是从jquery入手,可以先用js获取input标签的值,再拼接到url中,如下
$(document).ready(function(){ $("#b01").click(function(){ var num = $('input[name=phone_num]').val() // 获取phone输入框的值 console.log(num) htmlobj=$.ajax({url:"http://10.237.4.83:5000/phone?num="+num,async:false}); // 把参数num的值拼接到url中 $("#result").html(htmlobj.responseText); }); });
get请求也可以这样写
$(document).ready(function(){
$("#b02").click(function(){
var num = $('input[id=id_num]').val()
var data = { //定义data参数值
"num": num
}
console.log(num)
htmlobj=$.ajax({
type: 'get',
url:"http://10.237.4.83:5000/id",
data: data,
async:false});
$("#result").html(htmlobj.responseText);
});
});
最后看一下实现效果:
综上,代码改造全部完成,完整代码如下:
app.py
1 from flask import Flask, redirect, url_for, render_template, request 2 import random 3 import faker 4 import json 5 # import emoji 6 7 app = Flask(__name__) 8 fake = faker.Faker(locale='zh_CN') # 初始化,指定生成中文格式数据 9 10 11 @app.route('/index') 12 def index(): 13 return render_template("test.html") 14 15 16 def create_phone(num): 17 """生成电话""" 18 19 phones = [fake.phone_number() for _ in range(int(num))] # 列表推导,把生成的数据组成一个列表 20 # self.info.delete(1.0, "end") # 输出翻译内容前,先清空输出框的内容 21 # self.info.insert('end', phones) # 将翻译结果添加到输出框中 22 return " ".join(phones) 23 24 25 @app.route('/phone', methods=['POST', 'GET']) 26 def phone(): 27 # return_dict = {'statusCode': '200', 'message': 'successful!', 'result': create_phone()} 28 # 29 # return json.dumps(return_dict, ensure_ascii=False) 30 num = request.args.get("num") 31 if num == "": 32 data = create_phone(5) 33 else: 34 data = create_phone(num) 35 return data 36 37 38 def create_id(num=5): 39 """生成身份证""" 40 identity_ids = [fake.ssn() for i in range(int(num))] 41 # self.info.delete(1.0, "end") # 输出翻译内容前,先清空输出框的内容 42 # self.info.insert('end', phones) # 将翻译结果添加到输出框中 43 return " ".join(identity_ids) 44 45 46 @app.route('/id', methods=['GET']) 47 def id(): 48 # return_dict = {'statusCode': '200', 'message': 'successful!', 'result': create_phone()} 49 # return json.dumps(return_dict, ensure_ascii=False) 50 num = request.args.get("num") 51 if num == "": 52 data = create_id(5) 53 else: 54 data = create_id(num) 55 return data 56 57 58 def create_name(num): 59 """生成姓名""" 60 names = [fake.name() for i in range(int(num))] # 生成多个 61 # self.info.delete(1.0, "end") # 输出翻译内容前,先清空输出框的内容 62 # self.info.insert('end', phones) # 将翻译结果添加到输出框中 63 return " ".join(names) 64 65 66 @app.route('/name', methods=['GET']) 67 def name(): 68 # return_dict = {'statusCode': '200', 'message': 'successful!', 'result': create_phone()} 69 # return json.dumps(return_dict, ensure_ascii=False) 70 num = request.args.get("num") 71 if num == "": 72 data = create_name(20) 73 else: 74 data = create_name(num) 75 return data 76 77 78 def create_text(): 79 """生成一段文本""" 80 paragraph = fake.paragraphs(nb=5) # 生成多段话 81 paragraphs = ''.join(paragraph) # 组合成一句话 82 return "".join(paragraphs) 83 84 85 @app.route('/text', methods=['GET']) 86 def text(): 87 # return_dict = {'statusCode': '200', 'message': 'successful!', 'result': create_phone()} 88 # return json.dumps(return_dict, ensure_ascii=False) 89 data = create_text() 90 return data 91 92 93 def create_special(num): 94 """生成特殊字符""" 95 chars1 = ['~', '`', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '-', '+', '=', ',', '<', '>', '.', '?', 96 '/', '<h1 test>', 97 '¥', ' ', ' ', '{', '}', '[', ']', '|', '\\', ':', '"', 'α', 'π', '★', 'Ⅰ', 'Ⅱ', 'Ⅲ', 'Ⅳ', 'Ⅴ'] 98 chars2 = ['囃囄', '冁囆囇', '壅壆', '壈壌', '壍壐', '嬽嬾', '孁孂孄', '廗廘', '廙廛廜', '懚懛', '懜懝', '怼懠', '灖灗', '濲灙灚', '燿爀', '爁爂爃'] 99 100 c1 = random.sample(chars1, int(num)) 101 c2 = random.sample(chars2, 1) 102 return ''.join(c1) + c2[0] 103 104 105 @app.route('/special', methods=['GET']) 106 def special(): 107 # return_dict = {'statusCode': '200', 'message': 'successful!', 'result': create_phone()} 108 # return json.dumps(return_dict, ensure_ascii=False) 109 num = request.args.get("num") 110 data = create_special(num) 111 return data 112 113 114 if __name__ == '__main__': 115 app.run()
base.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <link rel="stylesheet" href="{{ url_for('static', filename='base.css') }}" type="text/css"> 7 <script type="text/javascript" src="{{ url_for('static', filename='jquery-3.5.1.js') }}"></script> 8 </head> 9 <body> 10 <div class="left"> 11 <div class="b1"> 12 13 <form method="get" action=""> 14 <button type="button" id="b01">手机号码</button> 15 <label> 16 <input type="text" name="phone_num" id="pnone_num" value="" placeholder="请输入个数"> 17 </label> 18 </form> 19 20 </div> 21 22 <div class="b1"> 23 <form method="get" action=""> 24 <button type="button" id="b02">身份证ID</button> 25 <label> 26 <input type="text" name="card_id" id="id_num" value="" placeholder="请输入个数"> 27 </label> 28 </form> 29 </div> 30 31 <div class="b1"><button type="button" id="b03">人名</button> 32 <label> 33 <input type="text" name="name" value="" placeholder="请输入个数"> 34 </label> 35 </div> 36 <div class="b1"><button type="button" id="b04">一段文字</button></div> 37 <div class="b1"><button type="button" id="b05">特殊字符</button> 38 <label for=""><select name="special" id="select"> 39 <option value="5">5个</option> 40 <option value="10">10个</option> 41 <option value="20">20个</option> 42 </select></label> 43 </div> 44 45 <div class="b1"><button style="background-color:darkred;color: #fcfcfc" type="button" id="b07">清空输出</button></div> 46 </div> 47 48 <div ><label for="result"></label><textarea class="textera" name="" id="result" cols="103" rows="20"></textarea></div> 49 50 <script type="text/javascript"> 51 $(document).ready(function(){ 52 $("#b01").click(function(){ 53 var num = $('input[name=phone_num]').val() // 获取phone输入框的值 54 console.log(num) 55 htmlobj=$.ajax({url:"http://10.237.4.83:5000/phone?num="+num,async:false}); // 把参数num的值拼接到url中 56 $("#result").html(htmlobj.responseText); 57 }); 58 }); 59 60 $(document).ready(function(){ 61 $("#b02").click(function(){ 62 var num = $('input[id=id_num]').val() 63 console.log(num) 64 htmlobj=$.ajax({url:"http://10.237.4.83:5000/id?num="+num,async:false}); 65 $("#result").html(htmlobj.responseText); 66 }); 67 }); 68 69 $(document).ready(function(){ 70 $("#b03").click(function(){ 71 var num = $('input[name=name]').val() 72 htmlobj=$.ajax({url:"http://10.237.4.83:5000/name?num="+num,async:false}); 73 $("#result").html(htmlobj.responseText); 74 }); 75 }); 76 77 $(document).ready(function(){ 78 $("#b04").click(function(){ 79 htmlobj=$.ajax({url:"http://10.237.4.83:5000/text",async:false}); 80 $("#result").html(htmlobj.responseText); 81 }); 82 }); 83 84 $(document).ready(function(){ 85 $("#b05").click(function(){ 86 var num = $("#select option:selected").val(); //获取选中的项 87 htmlobj=$.ajax({url:"http://10.237.4.83:5000/special?num="+num,async:false}); 88 $("#result").html(htmlobj.responseText); 89 }); 90 }); 91 92 $(document).ready(function(){ 93 $("#b07").click(function(){ 94 $("#result").empty(); 95 }); 96 }); 97 98 99 function submitForm() { 100 // jquery 表单提交 101 return false; 102 } 103 104 105 </script> 106 </body> 107 </html>