Flask web開發 處理POST請求(登錄案例)


本文我們以一個登錄例子來說明Flask對 post請求的處理機制。

1、創建應用目錄,如

mkdir   example

cd example

2、在應用目錄下創建  run.py文件,內容如下

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)上面的代碼用到了幾個flask的方法

render_template : 將請求定位到模板文件上,處理模板文件后,將結果作為請求的響應返回

redirect:將請求的響應重定向到新的url上。上面的例子是,當登錄成功后,重定向到 home頁面。

url_for:根據參數生成url

2)request對象的使用

request對象包含了所有的請求信息,通過它可獲取所需要的請求信息。

3)app.route增加了methods參數,指明該url支持的http請求方式,默認是get方式。上面例子 /login即作為get,也作為post的請求目標。

 

3、在應用目錄下創建 templates目錄,在templates目錄下創建 login.html 和 home.html,內容分別如下:

1)login.html文件

<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <title>login</title>
  </head>
  <body>
    <form  style="margin:20px;border:1px solid red" 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 %}
        <h1 style="color:red">{{ error }}!</h1>
    {% endif %}
  </body>
</html>

2)home.html

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

4、啟動服務

在應用目錄下運行  python  run.py

 

5、測試訪問

http://192.168.142.138/login

注意:登錄成功后,會進入 http://192.168.142.138/home?username=admin 頁面

這個url顯示不好。可以通過session的方式來不需要將username傳入,而是在home.html中通過session獲取。

這個在后面的文章中介紹。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM