Python-day8
學習要有定位,明確目標地去學習。希望自己能堅持下去,並有所收穫---leaves(ps:開發的核心思想就是對數據的增、刪、改、查)
python07 -- python+mysql,前段html實現數據的更新,刪除
一、瀏覽器請求數據的方法
瀏覽器請求數據的方法有GET、POST、PUT、DELETE、HEADER五種方法,其中python中常用的方法位GET和POST兩種方法。GET與POST方法的具體區別如下。
GET,常用獲取數據,默認爲讀,瀏覽器訪問都是GET,前段GET請求,邏輯端通過request.args.get獲取指定參數的值[request.args可以獲取所有參數];
POST,常用於提交表單數據,寫數據,瀏覽器默認不支持直接的POST方式,一般通過變動設置,邏輯端路由中添加methods=["GET","POST"]和前端html中form標籤內添加action='/路徑'來實現。
##GET方法 url :/login?username=cc&userpwd=222 #獲取某一單一的參數值 request.args.get("username",None) ===>cc #獲取所有參數值(獲取數據結構類似字典) request.args ===》ImmutableMultiDict([('username', u'cc'), ('userpwd', u'222')]) ##POST方法 #主要提交表單數據 #獲取提交的某一個單一數值 request.form.get("name",None) ====> aaa #獲取提交的所有參數的值(獲取數據結構類似字典) request.form =====>ImmutableMultiDict([('password', u'aaa'), ('name', u'aaa')])
二、實現html前端POST方式提交表單數據
POST方法提交表單數據主要分兩步實現:
1.邏輯端路由監聽時添加post方法
2.前端html的form標籤中添加action='/路徑',此路徑要與邏輯端監聽路由一一致。
##具體實現post方法的代碼 1.flask邏輯端代碼 from flask import Flask,request,render_template,redirect app = Flask(__name__) @app.route('/') def index(): return redirect('/login') @app.route('/login',methods=["GET",'POST']) def login(): if request.method == "POST": print request.method print request.form.get("name",None) print request.form tmp_post = dict(request.form) print dict( (k,v[0]) for k ,v in tmp_post.items()) return render_template('login.html') if __name__ == "__main__": app.run(host='0.0.0.0',port=888,debug = True) 2.前端html代碼 <html> <form action='/login' method="POST"> <p>name<input type='text' name='name'></p> <p>password<input type='password' name='password'></p> <p> <input type="submit" value='login'></p> </form> </html>
2.2 POST(GET)方法獲取全部數據後的轉換
request模塊中method方法可以獲取使用的訪問方法。如 request.method 值可以爲GET或者POST
2.2.1 POST方法獲取的數據爲
在此不討論request.form.get("name",None)這種某個單一元素的數據轉換。
request.form獲取的數據爲ImmutableMultiDict([('password', u'aaa'), ('name', u'aaa')]),爲類字典格式使用dict轉換下可以變成字典轉換後的值類型爲{'password': [u'dddd'], 'name': [u'aaa']},不過此時字典value值爲元組。所以離我們真正想要的字典形式有點差距,可以使用字典生成式轉換下。
2.2.2 具體的轉換方法
request.form ====> ImmutableMultiDict([('password', u'dddd'), ('name', u'aaa')])
tmp_post = dict(request.form) ===> {'password': [u'dddd'], 'name': [u'aaa']}
dict( (k,v[0]) for k ,v in tmp_post.items()) ===> {'password': u'dddd', 'name': u'aaa'}
2.3 zip()函數
In [5]: help(zip) zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] ##使用zip生成字典 In [7]: zip(('name','age'),('Bob',14)) Out[7]: [('name', 'Bob'), ('age', 14)] In [8]: dict(zip(('name','age'),('Bob',14))) Out[8]: {'age': 14, 'name': 'Bob'} In [9]: dict(zip(('name','age','test'),('Bob',14,'job'))) Out[9]: {'age': 14, 'name': 'Bob', 'test': 'job'} In [10]: dict(zip(('name','age','test'),('Bob',14))) Out[10]: {'age': 14, 'name': 'Bob'} In [11]: dict(zip(('name','age'),('Bob',14,'job'))) Out[11]: {'age': 14, 'name': 'Bob'} In [12]:
三、flask+mysql+html貫通實現更新和刪除操作
3.1 更新、刪除的邏輯端以及前端html代碼
##flask邏輯端代碼 [root@test blog]# cat demo.py #!/usr/bin/python #coding:utf-8 from flask import Flask ,render_template,redirect,request import MySQLdb as mysql from datetime import datetime datas = mysql.connect(user='root',passwd='123456',db='reboot',charset='utf8') datas.autocommit(True) cur = datas.cursor() fields = ["id","name","name_cn","password","email","mobile","role","status","create_time"] app = Flask(__name__) def getNow(): now = datetime.now().strptime("%Y-%m-%d %H:%M:%S") return now @app.route('/user/userlist') def userlist(): sql = "select %s from %s" %(','.join(fields),'users') cur.execute(sql) res = cur.fetchall() users = [ dict((v,row[k]) for k ,v in enumerate(fields)) for row in res] return render_template('userlist.html',users = users) @app.route('/user/delete') def delete(): id = request.args.get('id',None) print id d_sql = "No id error" if id : d_sql = "DELETE from users where id = %s" % id cur.execute(d_sql) return redirect('/user/userlist') return render_template('test.html',errmes = d_sql) @app.route('/user/update',methods=['GET','POST']) def update(): if request.method == "POST": user = dict(request.form) user = dict((k,v[0]) for k ,v in user.items()) #print user ==>{'mobile': u'CCC', 'name_cn': u'ccccccc', 'id': u'2', 'name': u'cc', 'email': u'[email protected]'} #user.pop('id') tmp_list = [ "%s='%s'"%(k,v) for k,v in user.items() if k != "id"] #print tmp_list update_sql = "UPDATE users set %s where id=%s" %(','.join(tmp_list),user['id']) cur.execute(update_sql) return redirect('/user/userlist') else: id = request.args.get('id',None) print id select_sql = "No id error" if id : select_sql = "select %s from users where id = %s" %(','.join(fields),id) print select_sql cur.execute(select_sql) res = cur.fetchone() #print res ==>(2L, u'cc', u'cc', u'cC23 ', u'[email protected]', u'CCC', u'user', 0, datetime.datetime(2016, 11, 30, 16, 4, 33)) user = dict((v,res[k]) for k ,v in enumerate(fields)) #return redirect('/user/userlist') return render_template('userinfo.html',user = user) if __name__ == "__main__": app.run(host='0.0.0.0',port=888,debug=True) [root@test blog]# ##前端html代碼 [root@test blog]# cat templates/userlist.html <html> <p>userlist</p> <table border='1px'> <thead> <tr><th>Name</th> <th>Name_CN</th> <th>Email</th> <th>Mobile</th> <th>Role</th> <th>Status</th> <th>Create_Time</th> <th>Operate></th></tr> </thead> <tbody> {% for user in users %} <tr><input type='hidden' name='id' value={{ user.id }}><td>{{ user.name}}</td> <td>`user`.`name_cn`</td> <td>`user`.`email`</td> <td>`user`.`mobile`</td> <td>`user`.`role`</td> <td>`user`.`status`</td> <td>`user`.`create_time`</td> <td><a href='/user/update?id=`user`.`id`'>更新</a> <a href='/user/delete?id=`user`.`id`'>刪除</a></tr> {% endfor %} </tbody> </table> </html> [root@test blog]# [root@test blog]# cat templates/userinfo.html <html> <p>userinfo</p> <form action="/user/update" method="POST"> <table> <tr> <td><input type="hidden" name='id' value=`user`.`id` ></td> </tr> <tr> <td>Name<input type='text' name='name' value=`user`.`name`></td> </tr> <tr> <td>Name_CN<input type='text' name='name_cn' value =`user`.`name_cn`></td> </tr> <tr> <td>Email<input type='text' name='email' value=`user`.`email`></td> </tr> <tr> <td>Mobile<input type='text' name='mobile' value=`user`.`mobile`></td> </tr> <tr> <td>Role<select > {% if user.role == "admin" %} <option value = 'admin'>管理員</option> {% elif user.role == "sa" %} <option value = 'sa'>運 維</option> {% else %} <option value = 'user'>普通用戶</option> {% endif %} </select> </td> </tr> <tr> <td>status<select > {% if user.status == 0 %} <option value = 0>正常</option> {% else %} <option value = 1>鎖定</option> {% endif %} </select> </tr> <tr><input type="submit" value='確認修改'></td></tr> </form> </html> [root@test blog]#
3.2 更新操作剖析
1.通過userlist獲取到所有數據庫中的數據以後,在userlist.html中展示出來,展示的時候添加一欄超鏈接<td><a href='/user/update?id=`user`.`id`'>更新</a> <a href='/user/delete?id=`user`.`id`'>刪除</a></tr>可以實現更新刪除兩個選項。當點擊更新按鈕後的步驟爲,獲取更新的頁面,將自己點擊更新的那條元素的信息塞到頁面對應的地方,更改我們想要的信息後,點擊確認按鈕post到邏輯端進行修改,然後跳轉回userlist的用戶列表界面。
2.userlist的html前端代碼以及訪問截圖
3.點擊更新後跳轉頁面
4.點擊更新頁面中的確認按鈕後傳遞到邏輯端進行操作
3.3 更新操作總結
3.3.1 更新的大體流程分爲兩步:
I:GET獲取更新用戶信息後渲染到html頁面,便於用戶自己更改信息
II:POST將更改後的信息提交到邏輯端處理
3.3.2 更新的userinfo.html前端中,input標籤內要記得寫name參數,get請求是value值要爲用戶從數據庫中查找出來的數據,form標籤中的action='/路徑'與監聽路由一直,使得POST提交表單數據時能得到正確的處理。
3.3.3 html前端中的下拉框實現
<tr> <td>Role<select > {% if user.role == "admin" %} <option value = 'admin'>管理員</option> {% elif user.role == "sa" %} <option value = 'sa'>運 維</option> {% else %} <option value = 'user'>普通用戶</option> {% endif %} </select> </td> </tr>
3.4 刪除操作
刪除操作同更新,不過刪除只需要一步,跟進用戶id號刪除。
具體步驟如下:GET方法獲取到用戶id號,拼接sql語句,邏輯端刪除用戶。完成刪除操作
3.5 思路
開發中整體核心思想就是增、刪、改、查這幾種數據操作,不同的是後端查詢獲取數據是通過數據庫還是API,開發的重點是思想。思想又分爲技術思路和項目思路。
技術思路--增刪改查
項目思路--用戶管理系統、CMDB、監控系統等等。(主要涉及系統的功能要求,技術實現。比如常規的線上用戶管理系統修改密碼肯定是單獨出來的一個功能)