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

創(chuàng)新互聯(lián)建站是一家以網(wǎng)站建設(shè)公司、網(wǎng)頁(yè)設(shè)計(jì)、品牌設(shè)計(jì)、軟件運(yùn)維、網(wǎng)站推廣、小程序App開發(fā)等移動(dòng)開發(fā)為一體互聯(lián)網(wǎng)公司。已累計(jì)為成都三輪攪拌車等眾行業(yè)中小客戶提供優(yōu)質(zhì)的互聯(lián)網(wǎng)建站和軟件開發(fā)服務(wù)。
運(yùn)行環(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)建一個(gè)類,用來(lái)通過(guò)sql語(yǔ)句查詢結(jié)果實(shí)例化對(duì)象用 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個(gè)方法是flask_login需要的4個(gè)驗(yàn)證方式 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ù)庫(kù)的模塊 maxconnections=6, # 連接池允許的連接數(shù),0和None表示不限制連接數(shù) mincached=2, # 初始化時(shí),鏈接池中至少創(chuàng)建的空閑的鏈接,0表示不創(chuàng)建 maxcached=5, # 鏈接池中最多閑置的鏈接,0和None不限制 maxshared=3, # 鏈接池中最多共享的鏈接數(shù)量,0和None表示全部共享。PS: 無(wú)用,因?yàn)閜ymysql和MySQLdb等模塊的 threadsafety都為1,所有值無(wú)論設(shè)置為多少,_maxcached永遠(yuǎn)為0,所以永遠(yuǎn)是所有鏈接都共享。 blocking=True, # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報(bào)錯(cuò) maxusage=None, # 一個(gè)鏈接最多被重復(fù)使用的次數(shù),None表示制 setsession=[], # 開始會(huì)話前執(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() #通過(guò)連接池鏈接數(shù)據(jù)庫(kù) cursor = conn.cursor() #創(chuàng)建游標(biāo) cursor.execute(sql, args) #執(zhí)行sql語(yǔ)句 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
#通過(guò)用戶名及密碼查詢用戶對(duì)象
@classmethod
def login_auth(cls,username,password):
print('login_auth')
result={'isAuth':False}
model= User_model.User_mod() #實(shí)例化一個(gè)對(duì)象,將查詢結(jié)果逐一添加給對(duì)象的屬性
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í)行的,需要通過(guò)用戶唯一的id找到用戶對(duì)象
@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() #實(shí)例化一個(gè)對(duì)象,將查詢結(jié)果逐一添加給對(duì)象的屬性
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語(yǔ)句的函數(shù)
@classmethod
def query(cls,sql,params = None):
result =dal.SQLHelper.fetch_one(sql,params)
return resultdenglu.py flask主運(yùn)行文件
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__)
#項(xiàng)目中設(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來(lái)取該用戶的其他屬性,這些屬性都是sql語(yǔ)句查來(lái)并賦值給對(duì)象的。
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ù),首先實(shí)例化form對(duì)象
然后通過(guò)form對(duì)象驗(yàn)證post接收到的數(shù)據(jù)格式是否正確
然后通過(guò)login_auth函數(shù),用username與password向數(shù)據(jù)庫(kù)查詢這個(gè)用戶,并將狀態(tài)碼以及對(duì)象返回
判斷狀態(tài)碼,如果正確則將對(duì)象傳入login_user中,然后就可以跳轉(zhuǎn)到正確頁(yè)面了'''
@login_manager.user_loader
def load_user(id):
return user_dal.User_Dal.load_user_byid(id)
'''
load_user是一個(gè)flask_login的回調(diào)函數(shù),在登陸之后,每訪問一個(gè)帶Login_required裝飾的視圖函數(shù)就要執(zhí)行一次,
該函數(shù)返回一個(gè)用戶對(duì)象,通過(guò)id來(lái)用sql語(yǔ)句查到的用戶數(shù)據(jù),然后實(shí)例化一個(gè)對(duì)象,并返回。
'''
#登陸成功跳轉(zhuǎn)的視圖函數(shù)
@app.route('/t')
@login_required
def hello_world():
print('登錄跳轉(zhuǎn)')
return 'Hello World!'
#隨便寫的另一個(gè)視圖函數(shù)
@app.route('/b')
@login_required
def hello():
print('視圖函數(shù)b')
return 'Hello b!'
if __name__ == '__main__':
app.run()簡(jiǎn)單總結(jié)一下:
通過(guò)flask的form表單驗(yàn)證數(shù)據(jù)格式
然后通過(guò)用戶名密碼從數(shù)據(jù)庫(kù)取用戶對(duì)象,將sql執(zhí)行結(jié)果賦值給一個(gè)實(shí)例化的對(duì)象
將這個(gè)對(duì)象傳給login_user,
然后成功跳轉(zhuǎn)。
注意要寫一個(gè)load_user回調(diào)函數(shù)嗎,返回的是通過(guò)id取到的數(shù)據(jù)庫(kù)并實(shí)例化的對(duì)象的用戶對(duì)象。
這個(gè)回調(diào)函數(shù)每次訪問帶login_required裝飾器的視圖函數(shù)都會(huì)被執(zhí)行。
還有一個(gè)就是current_user相當(dāng)于就是實(shí)例化的用戶對(duì)象,可以取用戶的其他屬性,注意,其他屬性僅限于sql語(yǔ)句查到的字段并添加給實(shí)例化對(duì)象的屬性。
相關(guān)推薦:
Flask框架如何連接數(shù)據(jù)庫(kù)
分享名稱:創(chuàng)新互聯(lián)Python教程:基于Flask框架如何實(shí)現(xiàn)用戶登錄功能
文章轉(zhuǎn)載:http://www.5511xx.com/article/copejco.html


咨詢
建站咨詢
