1. 程式人生 > 實用技巧 >Python + Flask 專案開發實踐系列《一》

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自動化測試等,微信搜尋公眾號:“無量測試之道”,或掃描下方二維碼:

新增關注,讓我們一起共同成長!