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

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

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

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

Step1: html 部分


<body>
<div class="container" style="width :90%">
    <div class="row" align="center"><span><h3>消息管理</h3></span></div>
    <div class="row" align="right">
        主要内容:<input type='text' id='contents' name='contents'>
        <button class="btn btn-warning" id="select">查询</button>
        <button class="btn btn-primary" id="adds">添加</button>
        <button class="btn btn-danger" id="delete">删除</button>
    </div>
    <hr>
    <div class="row" id="mainbody">
        <div class="table-responsive">
            <table>
                <thead>
                    <tr>
                        <th style="width : 50px">编号</th>
                        <th style="width : 100px">PMS名称</th>
                        <th style="width : 400px">主要内容</th>
                        <th style="width : 30px">状态</th>
                        <th style="width : 60px">备注</th>
                        <th style="width : 120px">创建时间</th>
                        <th style="width : 80px" align="center">操作项</th>
                    </tr>
                </thead>
                <tbody id="alldatas">
                </tbody>
            </table>
        </div>
    </div>
</div>
<div class="page" id="pageid"></div>
</body>

Step2:javascript部分


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


#表结构如下:
table1='''
create TABLE IF NOT EXISTS flask_info( 
 id  INTEGER   PRIMARY KEY AUTOINCREMENT,
    `pms_name` varchar(255) DEFAULT NULL,
    `content` varchar(1000) DEFAULT NULL,
    `status` varchar(255) DEFAULT NULL,
    `mark` varchar(255) DEFAULT NULL,
    `create_time` varchar(255) DEFAULT NULL
 );
'''
#数据库操作:
def get_count(sql): #获取sql返回总条数
    db = sqlite3.connect('test_flask.db')
    cur = db.cursor()
    result=cur.execute(sql).fetchall()
    print(result[0][0])
    cur.close()
    db.close()
    return result[0][0]

def get_data(sql1):#获取sql返回记录数
 db = sqlite3.connect('test_flask.db')
 cur = db.cursor()
 print(sql1)
 cur.execute(sql1)
 results=cur.fetchall()
 cloumn=get_table_colum()
 res = {}
 reslist = []
 print(results)
 for r in range(len(list(results))):
 for m in range(len(list(cloumn))):
 res[str(list(cloumn)[m])] = str(list(results)[r][m])
 reslist.append(res)
 res = {}
 print(reslist)
 cur.close()
 db.close()
 return reslist

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

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

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

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

猜你喜欢

转载自blog.csdn.net/weixin_41754309/article/details/107467183
今日推荐