溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在Flask web中處理POST請(qǐng)求登錄案例)

發(fā)布時(shí)間:2021-06-02 17:07:42 來(lái)源:億速云 閱讀:116 作者:Leah 欄目:開(kāi)發(fā)技術(shù)

怎么在Flask web中處理POST請(qǐng)求登錄案例)?很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。

1、創(chuàng)建應(yīng)用目錄,如

mkdir example
cd example

2、在應(yīng)用目錄下創(chuàng)建  run.py文件,內(nèi)容如下

from flask import Flask
from flask import render_template, redirect,url_for
from flask import request

app = Flask(__name__)

@app.route('/login', methods=['POST','GET'])
def login():
  error = None
  if request.method == 'POST':
    if request.form['username']=='admin':
      return redirect(url_for('home',username=request.form['username']))
    else:
      error = 'Invalid username/password'
  return render_template('login.html', error=error)

@app.route('/home')
def home():
  return render_template('home.html', username=request.args.get('username'))

if __name__ == '__main__':
  app.debug = True
  app.run('0.0.0.0',80)

上面的代碼解釋如下:

1)上面的代碼用到了幾個(gè)flask的方法

render_template : 將請(qǐng)求定位到模板文件上,處理模板文件后,將結(jié)果作為請(qǐng)求的響應(yīng)返回

redirect:將請(qǐng)求的響應(yīng)重定向到新的url上。上面的例子是,當(dāng)?shù)卿洺晒?,重定向?home頁(yè)面。

url_for:根據(jù)參數(shù)生成url

2)request對(duì)象的使用

request對(duì)象包含了所有的請(qǐng)求信息,通過(guò)它可獲取所需要的請(qǐng)求信息。

3)app.route增加了methods參數(shù),指明該url支持的http請(qǐng)求方式,默認(rèn)是get方式。上面例子 /login即作為get,也作為post的請(qǐng)求目標(biāo)。

3、在應(yīng)用目錄下創(chuàng)建 templates目錄,在templates目錄下創(chuàng)建 login.html 和 home.html,內(nèi)容分別如下:

1)login.html文件

<!DOCTYPE html>
<html lang="zh-CN">
 <head>
  <meta charset="utf-8">
  <title>login</title>
 </head>
 <body>
  <form  method="post" action="/login">
    <span>username:</span><input type="text" name="username" id="username"><br/>
    <span>password:</span><input type="password" name="password" id="password"><br/>
    <button type="submit" id="loginBtn">login</button>
  </form>
  {% if error %}
    <h2 >{{ error }}!</h2>
  {% endif %}
 </body>
</html>

2)home.html

<!DOCTYPE html>
<html lang="zh-CN">
 <head>
  <meta charset="utf-8">
  <title>home</title>
 </head>
 <body>
  <h2>wlcome {{username}} , this is home</h2>
 </body>
</html>

看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI