Python + Flask 项目开发实践系列《一》

欢迎关注【无量测试之道】公众号,回复【领取资源】,
Python编程学习资源干货、
Python+Appium框架APP的UI自动化、
Python+Selenium框架Web的UI自动化、
Python+Unittest框架API自动化、

资源和代码 免费送啦~
文章下方有公众号二维码,可直接微信扫一扫关注即可。

今天开始我们讲讲Flask Web实践项目开发中的首页内容列表加载功能是如何实现的。

Step1: html 部分

 1  
 2 <body>
 3 <div class="container" style="width :90%">
 4     <div class="row" align="center"><span><h3>消息管理</h3></span></div>
 5     <div class="row" align="right">
 6         主要内容:<input type='text' id='contents' name='contents'>
 7         <button class="btn btn-warning" id="select">查询</button>
 8         <button class="btn btn-primary" id="adds">添加</button>
 9         <button class="btn btn-danger" id="delete">删除</button>
10     </div>
11     <hr>
12     <div class="row" id="mainbody">
13         <div class="table-responsive">
14             <table>
15                 <thead>
16                     <tr>
17                         <th style="width : 50px">编号</th>
18                         <th style="width : 100px">PMS名称</th>
19                         <th style="width : 400px">主要内容</th>
20                         <th style="width : 30px">状态</th>
21                         <th style="width : 60px">备注</th>
22                         <th style="width : 120px">创建时间</th>
23                         <th style="width : 80px" align="center">操作项</th>
24                     </tr>
25                 </thead>
26                 <tbody id="alldatas">
27                 </tbody>
28             </table>
29         </div>
30     </div>
31 </div>
32 <div class="page" id="pageid"></div>
33 </body>

Step2:javascript部分

 1  
 2 <script type="application/javascript">
 3     //获取总记录数
 4     $(function () {
 5       var callback=function(p){//定义一个callback方法
 6           $.ajax({
 7           url: '/page/'+p,//规定发送请求的 URL
 8           type: 'GET',//规定请求的类型(GET 或 POST)
 9           dataType: 'json',//预期的服务器响应的数据类型
10           async:false, //表示请求是否异步处理
11           timeout: 1000,//设置本地的请求超时时间(以毫秒计)
12           cache: false, //表示浏览器是否缓存被请求页面
13           beforeSend: LoadFunction, //用于在向服务器发送请求前执行一些动作
14           error: ErrFunction,  //请求出错执行的函数
15           success: function (data) {//当请求成功时运行的函数
16               var jsons=data ? data : []; //定义一个变量当data有值时jsons=data,否则就为空
17               // 分页处理
18                 $("#pageid").pager({ //分页功能
19                pagenumber: jsons.pageNum,//表示初始页数
20                pagecount: jsons.pages,//表示总页数
21                totalcount: jsons.amount,//表示总记录数
22                buttonClickCallback: callback//表示点击分页数按钮调用的方法
23             });
24                lists=""
25               $.each(jsons.content, function (index, item) {//循环获取数据
26                     lists +="<tr>"+ //拼凑一段html片段
27                         "<td style='word-wrap:break-word;word-break:break-all; '><input type='checkbox' id='itemid' name='testid' value='"+item.id+"'>"+item.id+"</td>"+
28                         "<td style='word-wrap:break-word;word-break:break-all; '>"+item.pms_name+"</td>"+
29                         "<td style='word-wrap:break-word;word-break:break-all; '>"+item.content+"</td>"+
30                         "<td style='word-wrap:break-word;word-break:break-all; '>"+item.status+"</td>"+
31                         "<td style='word-wrap:break-word;word-break:break-all; '>"+item.mark+"</td>"+
32                         "<td style='word-wrap:break-word;word-break:break-all; '>"+item.create_time+"</td>"+
33                         "<td style='word-wrap:break-word;word-break:break-all; '>" +
34                         "<button class='btn btn-info' id='update' align='center' onclick='update($(this))'>修改</button>&nbsp&nbsp"+
35                         "<button class='btn btn-warning' id='updateother' align='center' onclick='detail($(this))'>查看详情</button>" +
36                         "</td>"
37                     "</tr>"
38               });
39               $("#alldatas").html(lists);//设置或返回所选元素的内容(包括 HTML 标记)
40           }
41       })}
42       function LoadFunction() {//上面调用的实现函数
43           $("#alldatas").html('加载的数据未找到,请重新添加!...');//设置或返回所选元素的内容(包括 HTML 标记)
44       }
45       function ErrFunction() {//上面调用的实现函数
46           alert("数据加载失败!!!!");//设置或返回所选元素的内容(包括 HTML 标记)
47       }
48       callback(1) //页面加载完成后自执行
49   });
50 </script>

Step3:Python+Flask 部分

 
@app.route('/page/<page>',methods=['GET'])
def pageapi(page):
    '''
    All_page:总页数,创建页码的根据
    All_Record:数据总条数,All_Record/PageCount=All_page 得到总页数
    Current_page:当前请求的页码.传送给服务端
    PageCount:每页显示的条数,传送给服务端
    '''
    sql = "select count(*) from flask_info"
    PageCount=10
    All_Record = get_count(sql)
    if (int(All_Record) % int(PageCount) == 0):
        All_page = All_Record / PageCount
    else:
        All_page = All_Record / PageCount + 1
    tiao=(int(page)-1)*int(PageCount)
    # print "tiao:",tiao
    sql1="select id,pms_name,content,status,mark,create_time from flask_info order by create_time desc limit %s,%s"%(tiao,PageCount)
    content=get_data(sql1)
    pagedict={}
    pagedict['content']=content
    pagedict['pageNum']=page
    pagedict['pages']=All_page
    pagedict['amount']=All_Record
    return jsonify(pagedict)

Step4: db部分

 1  
 2 #表结构如下:
 3 table1='''
 4 create TABLE IF NOT EXISTS flask_info( 
 5  id  INTEGER   PRIMARY KEY AUTOINCREMENT,
 6     `pms_name` varchar(255) DEFAULT NULL,
 7     `content` varchar(1000) DEFAULT NULL,
 8     `status` varchar(255) DEFAULT NULL,
 9     `mark` varchar(255) DEFAULT NULL,
10     `create_time` varchar(255) DEFAULT NULL
11  );
12 '''
13 #数据库操作:
14 def get_count(sql): #获取sql返回总条数
15     db = sqlite3.connect('test_flask.db')
16     cur = db.cursor()
17     result=cur.execute(sql).fetchall()
18     print(result[0][0])
19     cur.close()
20     db.close()
21     return result[0][0]
22  
23 def get_data(sql1):#获取sql返回记录数
24  db = sqlite3.connect('test_flask.db')
25  cur = db.cursor()
26  print(sql1)
27  cur.execute(sql1)
28  results=cur.fetchall()
29  cloumn=get_table_colum()
30  res = {}
31  reslist = []
32  print(results)
33  for r in range(len(list(results))):
34  for m in range(len(list(cloumn))):
35  res[str(list(cloumn)[m])] = str(list(results)[r][m])
36  reslist.append(res)
37  res = {}
38  print(reslist)
39  cur.close()
40  db.close()
41  return reslist

最后页面首页数据展示如下图所示:

 

总结:本文共分为四个部分,分别是由 html+js+python and flask+db组成,主要是说明了页面首页数据如何加载,内容清晰明了,每行代码需要仔细阅读,尤其javascript代码部分,注释写得尤其的详细,大家可以对照以上各部分代码多动手实践。

备注:我的个人公众号已正式开通,致力于测试技术的分享,包含:大数据测试、功能测试,测试开发,API接口自动化、测试运维、UI自动化测试等,微信搜索公众号:“无量测试之道”,或扫描下方二维码:

 

 添加关注,让我们一起共同成长!

原文地址:https://www.cnblogs.com/Wu13241454771/p/13346205.html