flask框架實(shí)戰(zhàn)4-表單數(shù)據(jù)傳輸

1、實(shí)現(xiàn)表單數(shù)據(jù)傳輸

為了達(dá)到一個(gè)具有互動(dòng)效果的網(wǎng)站,我們?cè)谑醉撛黾右粋€(gè)用戶登錄和注冊(cè)的鏈接,當(dāng)點(diǎn)擊這個(gè)登錄鏈接時(shí)就彈出登錄頁面,輸入姓名和密碼,進(jìn)行登錄操作。通常情況下使用表單來實(shí)現(xiàn)用戶信息的提交,同時(shí)當(dāng)?shù)卿洺晒?,使用session會(huì)話技術(shù)保存住用戶名信息。
修改index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>welcome to 2023</title>
    <style> .rr{float:left;width:50%;}</style>
</head>
<body>
<div style="width:600px;height:30px">
    <div class="rr"> welcome to my webpage  </div>
    <div class="rr">
       {% if data != ''  %}     #如果存在data變量的值,就顯示用戶姓名,以及注銷鏈接
        <a href="#">{{ data}}</a>
        <a href="#">注銷</a>
    {% else %}                   #否則就顯示登錄與注冊(cè)鏈接
        <a href="#">登陸</a>
        <a href="#">注冊(cè)</a>
    {% endif %}

    </div>
    <div style="clear:both;"></div>
</div>
<img src="{{ url_for('static',filename='img/main.jpg')}}" alt="">
<hr>
<ul>
    <li><a href="/news">查看新聞</a></li>
    <li><a href="/product">查看產(chǎn)品</a></li>
</ul>
</body>
</html>

當(dāng)點(diǎn)擊登錄鏈接時(shí),路由指向main.py中的login,該函數(shù)直接跳轉(zhuǎn)到login.html頁面里。在main.py中這部分代碼如下:

@app.route('/login')
def loginpage():
    return render_template("login.html")

login.html里設(shè)計(jì)一個(gè)表單輸入,注意form的action指向路由

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>userlogin</title>
</head>
<body>
<center>
    <h3>用戶登錄頁面</h3>
    <div>
        <form action="/loginProcess" method="post">
        用戶名: <input type="text" name="nm"><br>
        用戶密碼: <input type="password" name="pwd"> <br>
        <input type="submit" name="submit" value="登錄">
        </form>
    </div>
</center>
</body>
</html>

form中的action路由指向?yàn)閘oginProcess,
此時(shí)我們?cè)趍ain.py中增加這個(gè)路由裝飾器及對(duì)應(yīng)的函數(shù),同時(shí)由于涉及表單數(shù)據(jù)的接收,此時(shí)就需要導(dǎo)入flask的request包,調(diào)用其form屬性,具體用法如下:

data=request.form #data為一個(gè)接收表單的數(shù)組對(duì)象
或者 name=request.form['nm'] #接收到用戶名文本框的輸入并賦值給name變量

此時(shí)loginProcess路由代碼如下:

@app.route('/loginProcess',methods=['POST','GET'])
def loginProcesspage():
    if request.method=='POST':
        nm=request.form['nm']     #獲取姓名文本框的輸入值
        pwd=request.form['pwd']   #獲取密碼框的輸入值
        if nm=='cr' and pwd=='123':
            return render_template("index.html",data=nm)   #使用跳轉(zhuǎn)html頁面路由
        else:
            return 'the username or userpwd does not match!'

這里的當(dāng)輸入值滿足條件時(shí),使用了render_template來進(jìn)行頁面渲染,實(shí)際上是不合適的。不過為了說明表單輸入的處理方式,我們先這樣運(yùn)行,如此就基本實(shí)現(xiàn)了表單輸入的接收。

運(yùn)行過程中當(dāng)在首頁點(diǎn)擊登錄時(shí),跳轉(zhuǎn)到login函數(shù)渲染的login.html頁面,在表單中輸入對(duì)應(yīng)內(nèi)容后,點(diǎn)擊提交就來到服務(wù)器文件中的loginProcess裝飾器路徑,在對(duì)應(yīng)的loginProcesspage函數(shù)中,使用request.form來接收表單的輸入。后面的跳轉(zhuǎn)先前采用的render_template是不合適的,如果輸入的正確時(shí)運(yùn)行后,網(wǎng)頁上的url仍然是http://127.0.0.1/loginProcess,而不是首頁url,說明render_templates來實(shí)現(xiàn)url跳轉(zhuǎn)是不合適的。
這里調(diào)整一下,選用redirect重定向方式,也就是將render_template修改為,需要import redirect, url_for :
return redirect(url_for('index'))

還是使用到url_for方法,尋找到對(duì)應(yīng)的路由處理函數(shù)。不過不像rendertemplate可以傳遞參數(shù),redirect默認(rèn)參數(shù)里沒有傳值功能,因此如這種用戶注冊(cè),需要使用一下會(huì)話session緩存技術(shù)。也就是將正確的用戶名保存到session數(shù)組變量中。使用的時(shí)候先從flask庫中導(dǎo)入session模塊,同時(shí)為了保證安全,還需要給定一個(gè)app.secret_key:

app.secret_key='any random string' #這里我們直接給定一個(gè)密鑰

然后在剛才登錄loginProcess代碼中增加一個(gè)session會(huì)話存儲(chǔ)功能:

@app.route('/loginProcess',methods=['POST','GET'])
def loginProcesspage():
    if request.method=='POST':
        nm=request.form['nm']
        pwd=request.form['pwd']
        if nm=='cr' and pwd=='123':
            session['username']=nm             #使用session存儲(chǔ)方式,session默認(rèn)為數(shù)組,給定key和value即可            
            return redirect(url_for('index'))  #重定向跳轉(zhuǎn)到首頁
        else:
            return 'the username or userpwd does not match!'

接下來在首頁index.html頁面中修改一下:

<div class="rr">
       {% if session['username'] == 'cao'  %}    <!--如果是cr就顯示注銷-->
        <a href="#">{{ session['username']}}</a>
        <a href="#">注銷</a>

這樣就完整實(shí)現(xiàn)了用戶的登錄,當(dāng)然這里的用戶目前只限定了一個(gè)人名cr。如下為用戶登錄界面以及登錄后首頁的效果。

image.png

--參考
https://zhuanlan.zhihu.com/p/104273184

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容