日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > windows >内容正文

windows

Flask Session 登录认证模块

發(fā)布時間:2023/11/27 windows 35 coder
生活随笔 收集整理的這篇文章主要介紹了 Flask Session 登录认证模块 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Flask 框架提供了強大的 Session 模塊組件,為 Web 應(yīng)用實現(xiàn)用戶注冊與登錄系統(tǒng)提供了方便的機制。結(jié)合 Flask-WTF 表單組件,我們能夠輕松地設(shè)計出用戶友好且具備美觀界面的注冊和登錄頁面,使這一功能能夠直接應(yīng)用到我們的項目中。本文將深入探討如何通過 Flask 和 Flask-WTF 構(gòu)建一個完整的用戶注冊與登錄系統(tǒng),以及如何對頁面進行優(yōu)化美化,提高用戶體驗。通過這一系統(tǒng),用戶能夠方便注冊賬戶、安全登錄,并且我們能夠有效管理用戶的會話信息,為 Web 應(yīng)用的用戶管理提供一種高效的解決方案。

什么是Session機制?

Session 是一種在 Web 應(yīng)用中用于存儲用戶特定信息的機制。它允許在用戶訪問網(wǎng)站時存儲和檢索信息,以便在用戶的不同請求之間保持狀態(tài)。Session 機制在用戶登錄、購物網(wǎng)站、個性化設(shè)置等場景中得到廣泛應(yīng)用,它為用戶提供了更加連貫和個性化的體驗。在 Flask 中,通過 Flask Session 模塊可以方便地使用 Session ,實現(xiàn)用戶狀態(tài)的維護和管理。

在 Web 開發(fā)中,HTTP 協(xié)議是無狀態(tài)的,即每個請求都是獨立的,服務(wù)器不會記住之前的請求信息。為了解決這個問題,引入了 Session 機制。基本思想是在用戶訪問網(wǎng)站時,服務(wù)器生成一個唯一的 Session ID,并將這個 ID 存儲在用戶的瀏覽器中(通常通過 Cookie)。同時,服務(wù)器端會保存一個映射,將 Session ID 與用戶的相關(guān)信息關(guān)聯(lián)起來,這樣在用戶的后續(xù)請求中,服務(wù)器就能根據(jù) Session ID 找到相應(yīng)的用戶信息,從而實現(xiàn)狀態(tài)的保持。

Session 的認證流程通常包括以下步驟:

  1. 用戶登錄: 用戶通過提供用戶名和密碼進行登錄。在登錄驗證成功后,服務(wù)器為該用戶創(chuàng)建一個唯一的 Session ID,并將這個 ID 存儲在用戶瀏覽器的 Cookie 中。
  2. Session 存儲: 服務(wù)器端將用戶的相關(guān)信息(如用戶 ID、權(quán)限等)與 Session ID 關(guān)聯(lián)起來,并將這些信息存儲在服務(wù)器端的 Session 存儲中。Session 存儲可以是內(nèi)存、數(shù)據(jù)庫或其他持久化存儲方式。
  3. Session ID 傳遞: 服務(wù)器將生成的 Session ID 發(fā)送給用戶瀏覽器,通常是通過 Set-Cookie 頭部。這個 Cookie 會在用戶的每次請求中被包含在 HTTP 頭中。
  4. 后續(xù)請求: 用戶在后續(xù)的請求中會攜帶包含 Session ID 的 Cookie。服務(wù)器通過解析請求中的 Session ID,從 Session 存儲中檢索用戶的信息,以恢復用戶的狀態(tài)。
  5. 認證檢查: 服務(wù)器在每次請求中檢查 Session ID 的有效性,并驗證用戶的身份。如果 Session ID 無效或過期,用戶可能需要重新登錄。
  6. 用戶登出: 當用戶主動注銷或 Session 過期時,服務(wù)器將刪除與 Session ID 關(guān)聯(lián)的用戶信息,用戶需要重新登錄。

總體而言,Session 的認證流程通過在客戶端和服務(wù)器端之間傳遞唯一的 Session ID,實現(xiàn)了用戶狀態(tài)的持久化和管理。這種機制使得用戶可以在多個請求之間保持登錄狀態(tài),提供了一種有效的用戶認證方式。在 Flask 中,開發(fā)者可以方便地使用 Flask 提供的 Session 模塊來實現(xiàn)這一流程。

Session 認證基礎(chǔ)

默認情況下,直接使用Session模塊即可實現(xiàn)Session登錄會話保持,該方式是將Session存儲到內(nèi)存中,程序重啟后即釋放,Session的設(shè)置一般可以通過使用session["username"]賦值的方式進行,如需驗證該Session的可靠性,則只需要調(diào)用session.get方法即可一得到特定字段,通過對字段的判斷即可實現(xiàn)認證機制。

如下是一個Flask后端代碼,運行后通過訪問http://127.0.0.1:5000進入到登錄這頁面。

from flask import Flask,session,render_template,request,Response,redirect,url_for
from functools import wraps
import os

app = Flask(__name__, static_folder="./template",template_folder="./template")
app.config['SECRET_KEY'] = os.urandom(24)

# 登錄認證裝飾器
def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get("username") != None and session.get("is_login") ==True:
            print("登陸過則繼續(xù)執(zhí)行原函數(shù)")
            return func(*args, **kwargs)
        else:
            print("沒有登錄則跳轉(zhuǎn)到登錄頁面")
            resp = Response()
            resp.status_code=200
            resp.data = "<script>window.location.href='/login';</script>"
            return resp
    return wrapper

@app.route("/login",methods=["GET","POST"])
def login():
    if request.method == "GET":
        html = """
                <form action="/login" method="post">
                    <p>賬號: <input type="text" name="username"></p>
                    <p>密碼: <input type="password" name="password"></p>
                    <input type="submit" value="登錄">
                </form>
                """
        return html

    if request.method == "POST":
        get_dict = request.form.to_dict()

        get_username = get_dict['username']
        get_password = get_dict['password']

        if (get_username == "lyshark" or get_username == "admin") and get_password == "123123":
            session["username"] = get_username
            session["is_login"] = True

            print("登錄完成直接跳到主頁")
            resp = Response()
            resp.status_code=200
            resp.data = "<script>window.location.href='/index';</script>"
            return resp
        else:
            return "登陸失敗"
    return "未知錯誤"

# 主頁菜單
@app.route("/index",methods = ["GET","POST"])
@login_required
def index():
    username = session.get("username")
    return "用戶 {} 您好,這是主頁面".format(username)

# 第二個菜單
@app.route("/get",methods = ["GET","POST"])
@login_required
def get():
    username = session.get("username")
    return "用戶 {} 您好,這是子頁面".format(username)

@app.route("/logout",methods = ["GET","POST"])
@login_required
def logout():
    username = session.get("username")

    # 登出操作
    session.pop("username")
    session.pop("is_login")
    session.clear()
    return "用戶 {} 已注銷".format(username)

if __name__ == '__main__':
    app.run()

程序運行后,當用戶訪問http://127.0.0.1:5000地址則會跳轉(zhuǎn)到login登陸頁面,此時如果用戶第一次訪問則會輸出如下所示的登陸信息;

通過輸入正確的用戶名lyshark和密碼123123則可以登錄成功,此處登錄的用戶是lyshark如下圖。

通過輸入不同的用戶登錄會出現(xiàn)不同的頁面提示信息,如下圖則是admin的主頁信息。

當我們手動輸入logout時則此時會退出登錄用戶,后臺也會清除該用戶的Session,在開發(fā)中可以自動跳轉(zhuǎn)到登出頁面;

Session 使用數(shù)據(jù)庫

通過結(jié)合 Session 與 SQLite 數(shù)據(jù)庫,我們可以實現(xiàn)一個更完善的用戶注冊、登錄以及密碼修改功能。在這個案例中,首先,用戶可以通過注冊表單輸入用戶名、密碼等信息,這些信息經(jīng)過驗證后將被存儲到 SQLite 數(shù)據(jù)庫中。注冊成功后,用戶可以使用相同的用戶名和密碼進行登錄。登錄成功后,我們使用 Flask 的 Session 機制將用戶信息保存在服務(wù)器端,確保用戶在訪問其他頁面時仍然處于登錄狀態(tài)。

為了增加更多功能,我們還可以實現(xiàn)密碼修改的功能。用戶在登錄狀態(tài)下,通過密碼修改表單輸入新的密碼,我們將新密碼更新到數(shù)據(jù)庫中,確保用戶可以安全地更改密碼。這個案例綜合運用了 Flask、SQLite 和 Session 等功能,為 Web 應(yīng)用提供了一套完整的用戶管理系統(tǒng)。

from flask import Flask,request,render_template,session,Response
import sqlite3,os
from functools import wraps

app = Flask(__name__)

app.config['SECRET_KEY'] = os.urandom(24)

# 創(chuàng)建數(shù)據(jù)庫
def UserDB():
    conn = sqlite3.connect("./database.db")
    cursor = conn.cursor()
    create = "create table UserDB(" \
             "uid INTEGER primary key AUTOINCREMENT not null unique," \
             "username char(64) not null unique," \
             "password char(64) not null," \
             "email char(64) not null" \
             ")"
    cursor.execute(create)
    conn.commit()
    cursor.close()
    conn.close()

# 增刪改查簡單封裝
def RunSqlite(db,table,action,field,value):
    connect = sqlite3.connect(db)
    cursor = connect.cursor()

    # 執(zhí)行插入動作
    if action == "insert":
        insert = f"insert into {table}({field}) values({value});"
        if insert == None or len(insert) == 0:
            return False
        try:
            cursor.execute(insert)
        except Exception:
            return False

    # 執(zhí)行更新操作
    elif action == "update":
        update = f"update {table} set {value} where {field};"
        if update == None or len(update) == 0:
            return False
        try:
            cursor.execute(update)
        except Exception:
            return False

    # 執(zhí)行查詢操作
    elif action == "select":

        # 查詢條件是否為空
        if value == "none":
            select = f"select {field} from {table};"
        else:
            select = f"select {field} from {table} where {value};"

        try:
            ref = cursor.execute(select)
            ref_data = ref.fetchall()
            connect.commit()
            connect.close()
            return ref_data
        except Exception:
            return False

    # 執(zhí)行刪除操作
    elif action == "delete":
        delete = f"delete from {table} where {field};"
        if delete == None or len(delete) == 0:
            return False
        try:
            cursor.execute(delete)
        except Exception:
            return False
    try:
        connect.commit()
        connect.close()
        return True
    except Exception:
        return False

# 創(chuàng)建數(shù)據(jù)庫
@app.route("/create")
def create():
    UserDB()
    return "create success"

# 登錄認證裝飾器
def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get("username") != None and session.get("is_login") ==True:
            print("登陸過則繼續(xù)執(zhí)行原函數(shù)")
            return func(*args, **kwargs)
        else:
            print("沒有登錄則跳轉(zhuǎn)到登錄頁面")
            resp = Response()
            resp.status_code=200
            resp.data = "<script>window.location.href='/login';</script>"
            return resp
    return wrapper

# 用戶注冊頁面
@app.route("/register",methods=["GET","POST"])
def register():
    if request.method == "GET":
        html = """
                <form action="/register" method="post">
                    <p>賬號: <input type="text" name="username"></p>
                    <p>密碼: <input type="password" name="password"></p>
                    <p>郵箱: <input type="text", name="email"></p>
                    <input type="submit" value="用戶注冊">
                </form>
                """
        return html

    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        email = request.form.get("email")

        if RunSqlite("database.db","UserDB","select","username",f"username='{username}'") == []:
            insert = RunSqlite("database.db","UserDB","insert","username,password,email",f"'{username}','{password}','{email}'")
            if insert == True:
                return "創(chuàng)建完成"
            else:
                return "創(chuàng)建失敗"
        else:
            return "用戶存在"
        return "未知錯誤"

# 用戶登錄模塊
@app.route("/login",methods=["GET","POST"])
def login():
    if request.method == "GET":
        html = """
                <form action="/login" method="post">
                    <p>賬號: <input type="text" name="username"></p>
                    <p>密碼: <input type="password" name="password"></p>
                    <input type="submit" value="登錄">
                </form>
                """
        return html

    if request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")

        select = RunSqlite("database.db","UserDB","select","username,password",f"username='{username}'")
        if select != []:
            # 繼續(xù)驗證密碼
            if select[0][1] == password:
                session["username"] = username
                session["is_login"] = True

                print("登錄完成直接跳到主頁")
                resp = Response()
                resp.status_code = 200
                resp.data = "<script>window.location.href='/index';</script>"
                return resp
            else:
                return "密碼不正確"
        else:
            return "用戶不存在"
    return "未知錯誤"

# 修改密碼
@app.route("/modify",methods=["GET","POST"])
@login_required
def modify():
    if request.method == "GET":
        html = """
                <form action="/modify" method="post">
                    <p>新密碼: <input type="password" name="new_password"></p>
                    <input type="submit" value="修改密碼">
                </form>
                """
        return html

    if request.method == "POST":
        username = session.get("username")
        new_password = request.form.get("new_password")
        update = RunSqlite("database.db","UserDB","update",f"username='{username}'",f"password='{new_password}'")
        if update == True:
            # 登出操作
            session.pop("username")
            session.pop("is_login")
            session.clear()

            print("密碼已更新,請重新登錄")
            resp = Response()
            resp.status_code = 200
            resp.data = "<script>window.location.href='/login';</script>"
            return resp
        else:
            return "密碼更新失敗"
    return "未知錯誤"

# 主頁菜單
@app.route("/index",methods = ["GET","POST"])
@login_required
def index():
    username = session.get("username")
    return "用戶 {} 您好,這是主頁面".format(username)

# 第二個菜單
@app.route("/get",methods = ["GET","POST"])
@login_required
def get():
    username = session.get("username")
    return "用戶 {} 您好,這是子頁面".format(username)

@app.route("/logout",methods = ["GET","POST"])
@login_required
def logout():
    username = session.get("username")

    # 登出操作
    session.pop("username")
    session.pop("is_login")
    session.clear()
    return "用戶 {} 已注銷".format(username)

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

案例被運行后首先通過調(diào)用http://127.0.0.1:5000/create創(chuàng)建database.db數(shù)據(jù)庫,接著我們可以通過訪問/register路徑實現(xiàn)賬號注冊功能,如下我們注冊lyshark密碼是123123,輸出效果如下所示;

通過訪問/modify可實現(xiàn)對用戶密碼的修改,但在修改之前需要先通過/login頁面登錄后進行,否則會默認跳轉(zhuǎn)到用戶登錄頁面中;

使用WTForms登錄模板

在如上代碼基礎(chǔ)上,我們著重增加一個美化登錄模板,以提升用戶在注冊登錄流程中的整體體驗。通過引入WTF表單組件和Flask-WTF擴展,在前端實現(xiàn)了一個更友好的登錄頁面。

此登錄模板的設(shè)計考慮了頁面布局、顏色搭配、表單樣式等因素,以確保用戶在輸入用戶名和密碼時感到輕松自然。同時,我們利用Flask-WTF的驗證器功能,對用戶輸入的數(shù)據(jù)進行有效性檢查,保障了用戶信息的安全性。

首先,我們需要在template目錄下,創(chuàng)建register.html前端文件,用于用戶注冊,并寫入以下代碼。

<html>
<head>
    <link rel="stylesheet" >
    <link  rel="stylesheet" type="text/css" />
    <link  rel="stylesheet" type="text/css" />
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-offset-3 col-md-6">
                <form action="/register" method="post" class="form-horizontal">
                    {{ form.csrf_token }}

                    <span class="heading">用 戶 注 冊</span>
                    <div class="form-group">
                        {{ form.username }}
                        <i class="fa fa-user"></i>
                        <a href="/login" class="fa fa-question-circle"></a>
                    </div>
                    <div class="form-group">
                        {{ form.email }}
                        <i class="fa fa-envelope"></i>
                    </div>
                    <div class="form-group">
                        {{ form.password }}
                        <i class="fa fa-lock"></i>
                    </div>
                    <div class="form-group">
                        {{ form.RepeatPassword }}
                        <i class="fa fa-unlock-alt"></i>
                    </div>
                    {{ form.submit }}
                </form>
            </div>
        </div>
    </div>
</body>
</html>

接著,繼續(xù)創(chuàng)建login.html前端文件,用于登錄賬號時使用,并寫入以下代碼。

<html>
<head>
    <link rel="stylesheet" >
    <link  rel="stylesheet" type="text/css" />
    <link  rel="stylesheet" type="text/css" />
</head>
    <body>
        <div class="container">
            <div class="row">
                <div class="col-md-offset-3 col-md-6">
                    <form action="/login" method="post" class="form-horizontal">
                        {{ form.csrf_token }}

                        <span class="heading">用 戶 登 錄</span>
                        <div class="form-group">
                            {{ form.username }}
                            <i class="fa fa-user"></i>
                        </div>
                        <div class="form-group help">
                            {{ form.password }}
                            <i class="fa fa-lock"></i>
                            <a href="#" class="fa fa-question-circle"></a>
                        </div>
                        <div class="form-group">
                            <button type="submit" class="btn btn-success">登 錄 后 臺</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </body>
</html>

后臺代碼部分,我們需要在原代碼的基礎(chǔ)之上,增加對前端注冊和登錄頁面的渲染類,此處使用flask_wtf組件實現(xiàn)渲染生成,具體代碼如下。

from flask import Flask,request,render_template,session,Response
from functools import wraps
import sqlite3,os

from flask_wtf import FlaskForm
from wtforms import widgets,validators
from wtforms.validators import DataRequired,Regexp,DataRequired, Length, Email, EqualTo, NumberRange
from wtforms.fields import (StringField, PasswordField, DateField, BooleanField,DateTimeField,TimeField,
                            SelectField, SelectMultipleField, TextAreaField,FloatField,HiddenField,
                            RadioField, IntegerField, DecimalField, SubmitField, IntegerRangeField)

# app = Flask(__name__, static_folder="./template",template_folder="./template")
app = Flask(__name__)

app.config["SECRET_KEY"] = "d3d3Lmx5c2hhcmsuY29t"

# -----------------------------------------------------------------------------
# 創(chuàng)建數(shù)據(jù)庫
def UserDB():
    conn = sqlite3.connect("database.db")
    cursor = conn.cursor()
    create = "create table UserDB(" \
             "uid INTEGER primary key AUTOINCREMENT not null unique," \
             "username char(64) not null unique," \
             "password char(64) not null," \
             "email char(64) not null" \
             ")"
    cursor.execute(create)
    conn.commit()
    cursor.close()
    conn.close()

# 增刪改查簡單封裝
def RunSqlite(db,table,action,field,value):
    connect = sqlite3.connect(db)
    cursor = connect.cursor()

    # 執(zhí)行插入動作
    if action == "insert":
        insert = f"insert into {table}({field}) values({value});"
        if insert == None or len(insert) == 0:
            return False
        try:
            cursor.execute(insert)
        except Exception:
            return False

    # 執(zhí)行更新操作
    elif action == "update":
        update = f"update {table} set {value} where {field};"
        if update == None or len(update) == 0:
            return False
        try:
            cursor.execute(update)
        except Exception:
            return False

    # 執(zhí)行查詢操作
    elif action == "select":

        # 查詢條件是否為空
        if value == "none":
            select = f"select {field} from {table};"
        else:
            select = f"select {field} from {table} where {value};"

        try:
            ref = cursor.execute(select)
            ref_data = ref.fetchall()
            connect.commit()
            connect.close()
            return ref_data
        except Exception:
            return False

    # 執(zhí)行刪除操作
    elif action == "delete":
        delete = f"delete from {table} where {field};"
        if delete == None or len(delete) == 0:
            return False
        try:
            cursor.execute(delete)
        except Exception:
            return False
    try:
        connect.commit()
        connect.close()
        return True
    except Exception:
        return False

# -----------------------------------------------------------------------------
# 生成用戶注冊表單
class RegisterForm(FlaskForm):
    username = StringField(
        validators=[
            DataRequired(message='用戶名不能為空'),
            Length(min=1, max=15, message='用戶名長度必須大于%(min)d且小于%(max)d')
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'form-control', "placeholder":"輸入注冊用戶名"}
    )
    email = StringField(
        validators=[validators.DataRequired(message='郵箱不能為空'),validators.Email(message="郵箱格式輸入有誤")],
        render_kw={'class':'form-control', "placeholder":"輸入Email郵箱"}
    )
    password = PasswordField(
        validators=[
            validators.DataRequired(message='密碼不能為空'),
            validators.Length(min=5, message='用戶名長度必須大于%(min)d'),
            validators.Regexp(regex="[0-9a-zA-Z]{5,}",message='密碼不允許使用特殊字符')
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control', "placeholder":"輸入用戶密碼"}
    )
    RepeatPassword = PasswordField(
        validators=[
            validators.DataRequired(message='密碼不能為空'),
            validators.Length(min=5, message='密碼長度必須大于%(min)d'),
            validators.Regexp(regex="[0-9a-zA-Z]{5,}",message='密碼不允許使用特殊字符'),
            validators.EqualTo("password",message="兩次密碼輸入必須一致")
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control', "placeholder":"再次輸入密碼"}
    )
    submit = SubmitField(
        label="用 戶 注 冊", render_kw={ "class":"btn btn-success" }
    )

# 生成用戶登錄表單
class LoginForm(FlaskForm):
    username = StringField(
        validators=[
            validators.DataRequired(message=''),
            validators.Length(min=4, max=15, message=''),
            validators.Regexp(regex="[0-9a-zA-Z]{4,15}", message='')
        ],
        widget=widgets.TextInput(),
        render_kw={"class":"form-control", "placeholder":"請輸入用戶名或電子郵件"}
    )
    password = PasswordField(
        validators=[
            validators.DataRequired(message=''),
            validators.Length(min=5, max=15,message=''),
            validators.Regexp(regex="[0-9a-zA-Z]{5,15}",message='')
        ],
        widget=widgets.PasswordInput(),
        render_kw={"class":"form-control", "placeholder":"請輸入密碼"}
    )

# -----------------------------------------------------------------------------
# 創(chuàng)建數(shù)據(jù)庫
@app.route("/create")
def create():
    UserDB()
    return "create success"

# 登錄認證裝飾器
def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        if session.get("username") != None and session.get("is_login") ==True:
            print("登陸過則繼續(xù)執(zhí)行原函數(shù)")
            return func(*args, **kwargs)
        else:
            print("沒有登錄則跳轉(zhuǎn)到登錄頁面")
            resp = Response()
            resp.status_code=200
            resp.data = "<script>window.location.href='/login';</script>"
            return resp
    return wrapper

# 用戶注冊頁面
@app.route("/register",methods=["GET","POST"])
def register():
    form = RegisterForm(csrf_enabled = True)

    if request.method == "POST":
        if form.validate_on_submit():
            username = form.username.data
            password = form.RepeatPassword.data
            email = form.email.data
            print("用戶: {} 郵箱: {}".format(username,email))

            if RunSqlite("database.db", "UserDB", "select", "username", f"username='{username}'") == []:
                insert = RunSqlite("database.db", "UserDB", "insert", "username,password,email",
                                   f"'{username}','{password}','{email}'")
                if insert == True:
                    return "創(chuàng)建完成"
                else:
                    return "創(chuàng)建失敗"
            else:
                return "用戶存在"

    return render_template("register.html", form=form)

# 用戶登錄頁面
@app.route("/login",methods=["GET","POST"])
def login():
    form = LoginForm(csrf_enabled = True)

    if request.method == "POST":
        username = form.username.data
        password = form.password.data

        select = RunSqlite("database.db","UserDB","select","username,password",f"username='{username}'")
        if select != []:
            # 繼續(xù)驗證密碼
            if select[0][1] == password:
                session["username"] = username
                session["is_login"] = True

                print("登錄完成直接跳到主頁")
                resp = Response()
                resp.status_code = 200
                resp.data = "<script>window.location.href='/index';</script>"
                return resp
            else:
                return "密碼不正確"
        else:
            return "用戶不存在"

    return render_template("login.html", form=form)

# 修改密碼
@app.route("/modify",methods=["GET","POST"])
@login_required
def modify():
    if request.method == "GET":
        html = """
                <form action="/modify" method="post">
                    <p>新密碼: <input type="password" name="new_password"></p>
                    <input type="submit" value="修改密碼">
                </form>
                """
        return html

    if request.method == "POST":
        username = session.get("username")
        new_password = request.form.get("new_password")
        update = RunSqlite("database.db","UserDB","update",f"username='{username}'",f"password='{new_password}'")
        if update == True:
            # 登出操作
            session.pop("username")
            session.pop("is_login")
            session.clear()

            print("密碼已更新,請重新登錄")
            resp = Response()
            resp.status_code = 200
            resp.data = "<script>window.location.href='/login';</script>"
            return resp
        else:
            return "密碼更新失敗"
    return "未知錯誤"

# 主頁菜單
@app.route("/index",methods = ["GET","POST"])
@login_required
def index():
    username = session.get("username")
    return "用戶 {} 您好,這是主頁面".format(username)

# 第二個菜單
@app.route("/get",methods = ["GET","POST"])
@login_required
def get():
    username = session.get("username")
    return "用戶 {} 您好,這是子頁面".format(username)

@app.route("/logout",methods = ["GET","POST"])
@login_required
def logout():
    username = session.get("username")

    # 登出操作
    session.pop("username")
    session.pop("is_login")
    session.clear()
    return "用戶 {} 已注銷".format(username)

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

目錄結(jié)果如下圖所示;

當用戶訪問/register時,則可以看到通過flask_wtf渲染后的用戶注冊頁面,如下圖所示;

用戶訪問/login時,則是用戶登錄頁面,如下圖所示;

總結(jié)

以上是生活随笔為你收集整理的Flask Session 登录认证模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。