新聞中心
Flask框架如何通過Flask_login實現(xiàn)用戶登錄功能?下面給大家具體介紹一下步驟:

創(chuàng)新互聯(lián)建站是一家以網(wǎng)站建設(shè)公司、網(wǎng)頁設(shè)計、品牌設(shè)計、軟件運維、網(wǎng)站推廣、小程序App開發(fā)等移動開發(fā)為一體互聯(lián)網(wǎng)公司。已累計為成都三輪攪拌車等眾行業(yè)中小客戶提供優(yōu)質(zhì)的互聯(lián)網(wǎng)建站和軟件開發(fā)服務(wù)。
運行環(huán)境:
python3.5
Flask 0.12.2
Flask_Login 0.4.1
Flask-WTF 0.14.2
PyMySQL 0.8.0
WTForms 2.1
DBUtils 1.2
目錄結(jié)構(gòu):
直接看代碼,具體功能有注釋
Model/User_model.py
#創(chuàng)建一個類,用來通過sql語句查詢結(jié)果實例化對象用 class User_mod(): def __init__(self): self.id=None self.username=None self.task_count=None self.sample_count=None def todict(self): return self.__dict__ #下面這4個方法是flask_login需要的4個驗證方式 def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.id # def __repr__(self): # return '' % self.username
templates/login.html
Title
User_dal/dal.py
import pymysql from DBUtils.PooledDB import PooledDB POOL = PooledDB( creator=pymysql, # 使用鏈接數(shù)據(jù)庫的模塊 maxconnections=6, # 連接池允許的連接數(shù),0和None表示不限制連接數(shù) mincached=2, # 初始化時,鏈接池中至少創(chuàng)建的空閑的鏈接,0表示不創(chuàng)建 maxcached=5, # 鏈接池中最多閑置的鏈接,0和None不限制 maxshared=3, # 鏈接池中最多共享的鏈接數(shù)量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設(shè)置為多少,_maxcached永遠(yuǎn)為0,所以永遠(yuǎn)是所有鏈接都共享。 blocking=True, # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯 maxusage=None, # 一個鏈接最多被重復(fù)使用的次數(shù),None表示制 setsession=[], # 開始會話前執(zhí)行的命令列表。如:["set datestyle to ...", "set time zone ..."] ping=0, # ping MySQL服務(wù)端,檢查是否服務(wù)可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always host='192.168.20.195', port=3306, user='root', password='youpassword', database='mytest', charset='utf8' ) class SQLHelper(object): @staticmethod def fetch_one(sql,args): conn = POOL.connection() #通過連接池鏈接數(shù)據(jù)庫 cursor = conn.cursor() #創(chuàng)建游標(biāo) cursor.execute(sql, args) #執(zhí)行sql語句 result = cursor.fetchone() #取的sql查詢結(jié)果 conn.close() #關(guān)閉鏈接 return result @staticmethod def fetch_all(self,sql,args): conn = POOL.connection() cursor = conn.cursor() cursor.execute(sql, args) result = cursor.fetchone() conn.close() return result
相關(guān)推薦:《Python視頻教程》
User_dal/user_dal.py
from Model import User_model
from User_dal import dal
from User_dal import user_dal
class User_Dal:
persist = None
#通過用戶名及密碼查詢用戶對象
@classmethod
def login_auth(cls,username,password):
print('login_auth')
result={'isAuth':False}
model= User_model.User_mod() #實例化一個對象,將查詢結(jié)果逐一添加給對象的屬性
sql ="SELECT id,username,sample_count,task_count FROM User WHERE username ='%s' AND password = '%s'" % (username,password)
rows = user_dal.User_Dal.query(sql)
print('查詢結(jié)果>>>',rows)
if rows:
result['isAuth'] = True
model.id = rows[0]
model.username = rows[1]
model.sample_count = rows[2]
model.task_count = rows[3]
return result,model
#flask_login回調(diào)函數(shù)執(zhí)行的,需要通過用戶唯一的id找到用戶對象
@classmethod
def load_user_byid(cls,id):
print('load_user_byid')
sql="SELECT id,username,sample_count,task_count FROM User WHERE id='%s'" %id
model= User_model.User_mod() #實例化一個對象,將查詢結(jié)果逐一添加給對象的屬性
rows = user_dal.User_Dal.query(sql)
if rows:
result = {'isAuth': False}
result['isAuth'] = True
model.id = rows[0]
model.username = rows[1]
model.sample_count = rows[2]
model.task_count = rows[3]
return model
#具體執(zhí)行sql語句的函數(shù)
@classmethod
def query(cls,sql,params = None):
result =dal.SQLHelper.fetch_one(sql,params)
return resultdenglu.py flask主運行文件
from flask import Flask,render_template,redirect
from flask_login import LoginManager,login_user,login_required,current_user
from flask_wtf.form import FlaskForm
from wtforms import StringField, PasswordField, BooleanField
from wtforms.validators import Length,DataRequired,Optional
from User_dal import user_dal
app = Flask(__name__)
#項目中設(shè)置flask_login
login_manager = LoginManager()
login_manager.init_app(app)
app.config['SECRET_KEY'] = '234rsdf34523rwsf'
#flask_wtf表單
class LoginForm(FlaskForm):
username = StringField('賬戶名:', validators=[DataRequired(), Length(1, 30)])
password = PasswordField('密碼:', validators=[DataRequired(), Length(1, 64)])
remember_me = BooleanField('記住密碼', validators=[Optional()])
@app.route('/login',methods=['GET','POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
username = form.username.data
password = form.password.data
result = user_dal.User_Dal.login_auth(username,password)
model=result[1]
if result[0]['isAuth']:
login_user(model)
print('登陸成功')
print(current_user.username) #登錄成功之后可以用current_user來取該用戶的其他屬性,這些屬性都是sql語句查來并賦值給對象的。
return redirect('/t')
else:
print('登陸失敗')
return render_template('login.html',formid='loginForm',action='/login',method='post',form=form)
return render_template('login.html',formid='loginForm',action='/login',method='post',form=form)
'''登錄函數(shù),首先實例化form對象
然后通過form對象驗證post接收到的數(shù)據(jù)格式是否正確
然后通過login_auth函數(shù),用username與password向數(shù)據(jù)庫查詢這個用戶,并將狀態(tài)碼以及對象返回
判斷狀態(tài)碼,如果正確則將對象傳入login_user中,然后就可以跳轉(zhuǎn)到正確頁面了'''
@login_manager.user_loader
def load_user(id):
return user_dal.User_Dal.load_user_byid(id)
'''
load_user是一個flask_login的回調(diào)函數(shù),在登陸之后,每訪問一個帶Login_required裝飾的視圖函數(shù)就要執(zhí)行一次,
該函數(shù)返回一個用戶對象,通過id來用sql語句查到的用戶數(shù)據(jù),然后實例化一個對象,并返回。
'''
#登陸成功跳轉(zhuǎn)的視圖函數(shù)
@app.route('/t')
@login_required
def hello_world():
print('登錄跳轉(zhuǎn)')
return 'Hello World!'
#隨便寫的另一個視圖函數(shù)
@app.route('/b')
@login_required
def hello():
print('視圖函數(shù)b')
return 'Hello b!'
if __name__ == '__main__':
app.run()簡單總結(jié)一下:
通過flask的form表單驗證數(shù)據(jù)格式
然后通過用戶名密碼從數(shù)據(jù)庫取用戶對象,將sql執(zhí)行結(jié)果賦值給一個實例化的對象
將這個對象傳給login_user,
然后成功跳轉(zhuǎn)。
注意要寫一個load_user回調(diào)函數(shù)嗎,返回的是通過id取到的數(shù)據(jù)庫并實例化的對象的用戶對象。
這個回調(diào)函數(shù)每次訪問帶login_required裝飾器的視圖函數(shù)都會被執(zhí)行。
還有一個就是current_user相當(dāng)于就是實例化的用戶對象,可以取用戶的其他屬性,注意,其他屬性僅限于sql語句查到的字段并添加給實例化對象的屬性。
相關(guān)推薦:
Flask框架如何連接數(shù)據(jù)庫
新聞名稱:創(chuàng)新互聯(lián)Python教程:基于Flask框架如何實現(xiàn)用戶登錄功能
URL標(biāo)題:http://fisionsoft.com.cn/article/copejco.html


咨詢
建站咨詢
