時(shí)間:2023-07-16 15:06:01 | 來源:網(wǎng)站運(yùn)營(yíng)
時(shí)間:2023-07-16 15:06:01 來源:網(wǎng)站運(yùn)營(yíng)
【Python成長(zhǎng)之路】從 零做網(wǎng)站開發(fā) -- 基于Flask和JQuery,實(shí)現(xiàn)表格管理平臺(tái):【寫在前面】from flask import Flaskapp = Flask(__name__) @app.route('/')def hello_world(): return "Hello world!" if __name__ == '__main__': app.run()
先聲明一個(gè)Flask框架的對(duì)象,然后定義路由'/',即URL地址為 http://127.0.0.1:5000/;如果定義路徑為‘/new’,那對(duì)應(yīng)的訪問地址需要改為http://127.0.0.1:5000/new。另外,@app.route是個(gè)裝飾器。app.run(debug=True,host="x.x.x.x",port="1234")
通過對(duì)app.run()方法的參數(shù)定義,分別實(shí)現(xiàn)了調(diào)試功能,訪問URL變更為 http://x.x.x.x:1234from flask import Flask,render_templateapp = Flask(__name__) @app.route('/')def hello_world(): return render_template('test.html') if __name__ == '__main__': app.run()
只需要導(dǎo)入render_template庫,并且在函數(shù)返回時(shí)改成對(duì)應(yīng)的方法即可。con = sqlite3.connect('material.db')
如果有數(shù)據(jù)庫material.db,則進(jìn)行連接數(shù)據(jù)庫的操作;如果沒有此數(shù)據(jù)庫,則先創(chuàng)建數(shù)據(jù)庫再進(jìn)行連接;label = ['ID','網(wǎng)絡(luò)IP','地址','責(zé)任人','聯(lián)系方式']content = ['1','10.10.10.10','杭州濱江','鵬哥','123456']def create(): sql = 'create table {0} ({1},{2},{3},{4},{5})'.format(tablename,label[0],label[1],label[2],label[3],label[4]) result = cur.execute(sql) con.commit() return True if result else False
簡(jiǎn)單描述為:create table 表名 (各字段名1,各字段名2……) sql = 'create table matrial_table ("ID" int[10] primary key not null )'
同理,其他字段也可以相同的方式進(jìn)行類型、長(zhǎng)度的限制。def insert(): sql = 'insert into {0} ({1},{2},{3},{4},{5}) values({6},"{7}","{8}","{9}","{10}")'.format(tablename,label[0],label[1], label[2],label[3],label[4],content[0],content[1],content[2],content[3],content[4]) result = cur.execute(sql) con.commit() return True if result else False
簡(jiǎn)單描述為:insert into 表名 (各字段名1,各字段名2……) values(數(shù)值1,數(shù)值2……)def query(): sql = 'select * from {0}'.format(tablename) result = cur.execute(sql) return list(result)
簡(jiǎn)單描述為:select XX,XX from 表名 where 字段名1="數(shù)值1"# coding=utf-8# @Auther : "鵬哥賊優(yōu)秀"# @Date : 2019/9/23# @Software : PyCharm from flask import Flask,render_templateimport sqlite3app = Flask(__name__)con = sqlite3.connect('material.db',check_same_thread=False) @app.route('/')def Material_Mangement(): # 獲取數(shù)據(jù)庫material_table表的內(nèi)容 cur = con.cursor() sql = 'select * from {0}'.format("material_table") cur.execute(sql) content = cur.fetchall() # 獲取數(shù)據(jù)庫表的表頭 labels = [tuple[0] for tuple in cur.description] return render_template('test.html',content=content,labels=labels) if __name__ == '__main__': app.run(debug=True)
動(dòng)態(tài)路由、sqlite3數(shù)據(jù)庫操作、調(diào)試模式的設(shè)置,這些知識(shí)請(qǐng)參考之前的博客。但有2個(gè)知識(shí)點(diǎn),我想再提下:<!doctype html><html lang="en"><head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>物料管理平臺(tái)</title></head><body><div class="row"> <div class="col-md-6 col-sm-12 col-xs-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3>表格管理平臺(tái)</h3> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> {% for i in labels %} <td>{{ i }}</td> {% endfor %} </tr> </thead> <tbody> {% for i in content %} <tr> {% for j in i %} <td>{{ j }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div><!-- Optional JavaScript --><!-- jQuery first, then Popper.js, then Bootstrap JS --><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script></body></html>
對(duì)應(yīng)的效果是這樣的:<!doctype html><html lang="en"><head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <title>表格管理平臺(tái)</title></head><body><div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3>表格管理平臺(tái)</h3> </div> <div class="panel-body"> <div class="table-responsive"> <table class="table table-striped table-bordered table-hover"> <thead> <tr> {% for i in labels %} <td>{{ i }}</td> {% endfor %} </tr> </thead> <tbody> {% for i in content %} <tr> {% for j in i %} <td>{{ j }}</td> {% endfor %} <td><input type="button" value="編輯"></td> <td><input type="submit" value="提交"></td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div><!-- Optional JavaScript --><!-- jQuery first, then Popper.js, then Bootstrap JS --><script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script><script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script><script> (function(){ $('input[type="button"]').on('click', function(){ var $this = $(this), edit_status = $this.attr('edit_status'), status_value = edit_status && 1 == edit_status ? 0 : 1, $td_arr = $this.parent().prevAll('td'); $this.val(1 == status_value ? '完成' : '編輯').attr('edit_status', status_value); $.each($td_arr, function(){ var $td = $(this); if(1 == status_value) { $td.html('<input type="text" value="'+$td.html()+'">'); } else if(0 == status_value){ $td.html($td.find('input[type=text]').val()); } }); }); })();</script></body></html>
相比于第 2步時(shí)的html文件,這次我主要添加了2塊內(nèi)容:<td><input type="button" value="編輯"></td> <td><input type="submit" value="提交"></td>
將這兩行代碼放在表格每行最后,就會(huì)生成相應(yīng)的按鈕<script> (function(){ <!--定義屬于是 button的按鈕在點(diǎn)擊后,產(chǎn)生下面的function功能--> $('input[type="button"]').on('click', function(){ <!--獲取當(dāng)前事件,并進(jìn)行當(dāng)前按鈕的狀態(tài),如果是編輯狀態(tài),就進(jìn)行將每個(gè)單元格設(shè)置成可輸入狀態(tài)--> var $this = $(this), edit_status = $this.attr('edit_status'), status_value = edit_status && 1 == edit_status ? 0 : 1, $td_arr = $this.parent().prevAll('td'); $this.val(1 == status_value ? '完成' : '編輯').attr('edit_status', status_value); <!--如果單元格是可編輯狀態(tài),獲取每列元素的值,并在最后html表格上進(jìn)行展示--> $.each($td_arr, function(){ var $td = $(this); if(1 == status_value) { $td.html('<input type="text" value="'+$td.html()+'">'); <!--如果按鈕狀態(tài)是完成狀態(tài),直接展示單元內(nèi)的值--> } else if(0 == status_value){ $td.html($td.find('input[type=text]').val()); } }); }); })();</script>
細(xì)心的同學(xué)會(huì)發(fā)現(xiàn),我在點(diǎn)擊”提交“按鈕時(shí),什么都沒 發(fā)生。是的,”提交“功能,我將在下一個(gè)章節(jié)中進(jìn)行介紹。<script> (function(){ <!--定義屬性是submit的按鈕在點(diǎn)擊后,產(chǎn)生下面的function功能--> $('input[type="submit"]').on('click', function(){ <!--獲取當(dāng)前行的id --> var td = event.srcElement.parentElement; var rownum = td.parentElement.rowIndex; <!--獲取html表格元素 --> var tab = document.getElementById("test"); <!--將每個(gè)單元格元素進(jìn)行取值,并以字典形式傳給后臺(tái) --> var data = { "ID":tab.rows[rownum].cells[0].innerHTML, "網(wǎng)絡(luò)IP":tab.rows[rownum].cells[1].innerHTML, "地址":tab.rows[rownum].cells[2].innerHTML, "責(zé)任人":tab.rows[rownum].cells[3].innerHTML, "聯(lián)系方式":tab.rows[rownum].cells[4].innerHTML, }; alert("提交成功!") $.ajax({ type: "get", url: "/edit", data: data, dataType: "json" }); }); })();
(2)后臺(tái)對(duì)提交后的數(shù)據(jù)進(jìn)行讀取,并寫數(shù)據(jù)庫@app.route('/edit', methods=['get'])def edit(): label = ['ID', '網(wǎng)絡(luò)IP', '地址', '責(zé)任人', '聯(lián)系方式'] content = [request.args.get(i) for i in label] print(content) sql = 'update {0} set {1}="{6}",{2}="{7}",{3}="{8}",{4}="{9}" where {5}={10}'.format('material_table', label[1], label[2], label[3],label[4],label[0],content[1],content[2],content[3],content[4],content[0]) cur = con.cursor() cur.execute(sql) con.commit() return "數(shù)據(jù)寫入成功!"
在實(shí)現(xiàn)“提交”功能時(shí),我主要遇到了以下幾個(gè) 坑:<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
我理解這行代碼的意思是聲明下面要JQuery庫,而不是其他JS庫。(可能理解有誤)var td = event.parentElement;var rownum = td.parentElement.rowIndex;
通過alert調(diào)試,發(fā)現(xiàn)點(diǎn)擊提交根本沒有反應(yīng);又改成var td = event.srcElement;var rownum = td.parentElement.rowIndex;
結(jié)果是獲取不到任何內(nèi)容tab.rows[0].cells[0].innerHTML
在獲取單元格內(nèi)數(shù)據(jù)時(shí),最驗(yàn)證的是我獲取不到tab,即表格元素。因?yàn)槲以葲]有在表格元素里加id,即<td><input type="button" value="新增" id="create"></td><br>
如果前面 的html能看懂了,這行是不難理解的。<script> (function () { $('input[id="create"]').on('click', function(){ var editTable=document.getElementById("tbody"); var tr=document.createElement("tr"); var td1=document.createElement("td"); td1.innerHTML=""; tr.appendChild(td1); editTable.appendChild(tr);
首先定義tr元素,然后在tr元素中再追加td元素。如果表格里有多列數(shù)據(jù),那只需要重復(fù)td1的寫法,進(jìn)行復(fù)制粘貼就可以了。td1.innerHTML="input[type=text] /";
3、如何動(dòng)態(tài)添加“編輯”、“提交”按鈕,下面以“編輯”為例var td9 = document.createElement("td")var myedit =document.createElement("input");myedit.type = "button";myedit.value = "編輯"myedit.id = "edit"td9.appendChild(myedit)
添加方式和添加文本框方式是一樣的,只是需要注意元素類型是Input,并且要補(bǔ)充下元素的type/value/id。$('input[id="submit"]').on('click', function(){ alert("test")}
關(guān)于動(dòng)態(tài)添加的按鈕進(jìn)行事件綁定有很多帖子,有用Live方法的,有用$(document).on('click','.edit',function()方法的,其實(shí)不用這么麻煩,和正常的“提交”寫法是完全一樣的。 var tab = document.getElementById("test"); var rownum = td1.parentElement.rowIndex; $('input[id="submit"]').on('click', function(){ var data = { "ID":tab.rows[rownum].cells[0].innerHTML, }; alert("新增成功!") $.ajax({ type: "get", url: "/create", data: data, dataType: "json" }); });
這段代碼和提交功能的實(shí)現(xiàn)是一樣的,大同小異。關(guān)鍵詞:實(shí)現(xiàn),平臺(tái),管理,表格,成長(zhǎng)
客戶&案例
營(yíng)銷資訊
關(guān)于我們
客戶&案例
營(yíng)銷資訊
關(guān)于我們
微信公眾號(hào)
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。