1. 程式人生 > >Flask Web開發入門(一)之簡單的登入驗證

Flask Web開發入門(一)之簡單的登入驗證

Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.

我們的目標是通過Flask實現一個簡單的web系統,系統需要使用者登入,未登入使用者無法訪問授權頁面,因此,我們定義頁面如下:

  • index.html預設首頁,需要登入授權訪問
  • login.html登入頁,輸入使用者名稱和密碼
  • error.html, 40X.html 錯誤頁,顯示錯誤資訊
  • detail.html詳情頁,需要登入授權訪問

未使用Flask-Login模組進行會話管理時,我們可以通過簡單的session控制來實現基本的授權訪問控制

這是基本的程式碼組織結構:
這裡寫圖片描述

  • 前臺頁面登入頁面程式碼如下:
<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
使用者登入</title> <link rel="stylesheet" type="text/css" href="
{{ url_for('static', filename='css/styles.css') }}"/> <link rel="shortcut icon" href="{{ url_for('static', filename='images/favicon.ico')}}"/> </head> <body> <div class="htmleaf-container"> <div class
="wrapper">
<div class="container"> <h1>Welcome</h1> <form class="form" method="post" action="/" onsubmit="return doLogin();"> <input type="text" placeholder="Username" name="username" id="username"> <input type="password" placeholder="Password" name="password" id="password"> <button type="submit" id="login-button">Login</button> </form> </div> <ul class="bg-bubbles"> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </div> <script src="
{{ url_for('static', filename='js/jquery-2.1.1.min.js') }} " type="text/javascript"></script> <script> function doLogin() { var login = false; $.ajax({ url: '/login', data: "username=" + $("#username").val() + "&password=" + $("#password").val(), type: 'POST', contentType: 'application/x-www-form-urlencoded', async: false, success: function (d) { var status = d.status; if (status != undefined && status != '') { if (status == "-1") { alert("認證異常"); login = false; } else { login = true; } } else { alert("使用者名稱或密碼錯誤!"); login = false; } } }); return login; } </script> <div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';color:#000000"> <h1>管理後臺</h1> </div> </body>

注意,載入css和js的寫法,通過url_for載入static目錄下對應的檔案

 <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/styles.css') }}"/>

<script src="{{ url_for('static', filename='js/jquery-2.1.1.min.js') }} " type="text/javascript"></script>
  • 路由由方法login
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        logger.debug("login post method")
        username = request.form['username']
        password = request.form['password']

        if username == 'admin' and password == 'admin123':

            session['username'] = username
            session['password'] = password
            resp = make_response(render_template('index.html', name=username))
            resp.set_cookie('username', username)
            # return resp
            return jsonify({'status': '0', 'errmsg': '登入成功!'})
        else:
            # return redirect(url_for('error'))
            return jsonify({'status': '-1', 'errmsg': '使用者名稱或密碼錯誤!'})

    logger.debug("login get method")
    return render_template('login.html')

注意:為了簡單期間,我們將使用者名稱和密碼直接限定為固定值,後續,我們會有專門章節介紹資料庫讀取方式

 if username == 'admin' and password == 'admin123':
  • 路由方法index
    通過session判斷使用者是否登入:
@app.route('/', methods=['GET', 'POST'])
def index():
    logger.debug("index page")
    logger.debug("cookie name %s" % request.cookies.get('username'))

    if 'username' in session:
        logger.debug("login user is %s" % flask_login.current_user)
        logger.debug('Logged in as %s' % escape(session['username']))
        return render_template('index.html', name=session['username'])
    else:
        logger.debug("you are not logged in")
        return render_template('login.html')

至此,我們完成了一個簡單的web應用,後續,我們介紹如何使用Flask-Login進行會話管理