時(shí)間:2023-07-05 11:36:01 | 來源:網(wǎng)站運(yùn)營
時(shí)間:2023-07-05 11:36:01 來源:網(wǎng)站運(yùn)營
使用flask框架制作簡單的基于MySQL數(shù)據(jù)庫的搜索網(wǎng)頁:本小白一直沒學(xué)過網(wǎng)頁語言,研一才開始接觸python,現(xiàn)在導(dǎo)師讓制作個(gè)簡單的網(wǎng)頁,我也是用了些時(shí)間才搞明白。里面若有問題或錯(cuò)誤的,請留言?。?!<!DOCTYPE html><html><head> <meta charset="UTF-8"> <title>Title</title></head><body><form action="/gets/" method="post"> <p>搜索: <input type="text" name="question"></p> <input type="submit"></form></body></html>
其實(shí)我們不太用全懂html語言,只要知道個(gè)差不多就行,畢竟不是專門做網(wǎng)頁的,能實(shí)現(xiàn)我們簡單的需求即可。上面這段代碼是生成了一個(gè)搜索文本框。具體我就不講了,因?yàn)槲乙膊皇呛芮宄?。然后寫我們的主程序代碼:from flask import Flask,render_template,requestimport pymysqlapp = Flask(__name__)@app.route('/')def index(): return render_template('base.html')if __name__ == '__main__': app.run(debug=True,host='127.0.0.1',port='8080')
這個(gè)base.html文件就是剛才我們寫的,放在templates文件夾下。運(yùn)行后就會出現(xiàn)一個(gè)網(wǎng)址,點(diǎn)擊進(jìn)入,如圖:<!DOCTYPE html><html lang="cn-zh"><head> <meta charset="UTF-8"> <title>搜索結(jié)果展示</title></head><body> <center> <form action="/gets/" method="post"> <h1>搜索結(jié)果展示</h1> <hr> <table border="1px" width="400px"> <tr style="text-align:center"> <th>id</th> <th>姓名</th> <th>年齡</th> <th>城市</th> </tr> {% for i in items %} <tr style="text-align:center"> <td>{{ i.id }}</td> <td>{{ i.name }}</td> <td>{{ i.age }}</td> <td>{{ i.city }}</td> </tr> {% endfor %} </table> </form> </center></body></html>
這段代碼的意思就是將數(shù)據(jù)庫中的信息打印在網(wǎng)頁上。此時(shí)我的主程序代碼加入了另外一個(gè)函數(shù):from flask import Flask,render_template,requestimport pymysqlapp = Flask(__name__)@app.route('/')def index(): return render_template('base.html')@app.route('/gets/',methods=['POST'])def search(): conn = pymysql.connect(user='root', host='localhost', passwd='', db='test',cursorclass=pymysql.cursors.DictCursor) cur = conn.cursor() sql = "select * from database1" cur.execute(sql) datas = cur.fetchall() return render_template('search.html',items=datas)if __name__ == '__main__': app.run(debug=True,host='127.0.0.1',port='8080')
多了一個(gè)@app.route('/gets/',methods=['POST'])還有下面的search()函數(shù),當(dāng)然我們還沒做到搜索功能,這只是將MySQL數(shù)據(jù)庫中的信息打印在網(wǎng)頁上。def search(): conn = pymysql.connect(user='root', host='localhost', passwd='', db='test',cursorclass=pymysql.cursors.DictCursor) cur = conn.cursor() S = request.values.get('question') sql = "select * from database1 where name like '%"+S+"%'" cur.execute(sql) datas = cur.fetchall() return render_template('search.html',items=datas)
上面的search()函數(shù)經(jīng)過了修改,加入了S = request.values.get('question')這行代碼,它的功能就是得到輸入框的信息,后面的參數(shù)‘question’在base.html文件里定義的:關(guān)鍵詞:數(shù)據(jù),簡單,使用
客戶&案例
營銷資訊
關(guān)于我們
微信公眾號
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。