本文實例講述了Flask框架通過Flask_login實現用戶登錄功能。分享給大家供大家參考,具體如下:
通過Flask_Login實現用戶驗證登錄,并通過login_required裝飾器來判斷用戶登錄狀態來判斷是否允許訪問視圖函數。
運行環境:
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
目錄結構:
直接看代碼,具體功能有注釋
Model/User_model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#創建一個類,用來通過sql語句查詢結果實例化對象用 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 '<User %r>' % self.username |
templates/login.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < title >Title</ title > </ head > < body > < div class = "login-content" > < form class = "margin-bottom-0" action = "{{ action }}" method = "{{ method }}" id = "{{ formid }}" > {{ form.hidden_tag() }} < div class = "form-group m-b-20" > {{ form.username(class='form-control input-lg',placeholder = "用戶名") }} </ div > < div class = "form-group m-b-20" > {{ form.password(class='form-control input-lg',placeholder = "密碼") }} </ div > < div class = "checkbox m-b-20" > < label > {{ form.remember_me() }} 記住我 </ label > </ div > < div class = "login-buttons" > < button type = "submit" class = "btn btn-success btn-block btn-lg" >登 錄</ button > </ div > </ form > </ div > </ body > </ html > |
User_dal/dal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
import pymysql from DBUtils.PooledDB import PooledDB POOL = PooledDB( creator = pymysql, # 使用鏈接數據庫的模塊 maxconnections = 6 , # 連接池允許的最大連接數,0和None表示不限制連接數 mincached = 2 , # 初始化時,鏈接池中至少創建的空閑的鏈接,0表示不創建 maxcached = 5 , # 鏈接池中最多閑置的鏈接,0和None不限制 maxshared = 3 , # 鏈接池中最多共享的鏈接數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。 blocking = True , # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯 maxusage = None , # 一個鏈接最多被重復使用的次數,None表示無限制 setsession = [], # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."] ping = 0 , # ping MySQL服務端,檢查是否服務可用。# 如: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() #通過連接池鏈接數據庫 cursor = conn.cursor() #創建游標 cursor.execute(sql, args) #執行sql語句 result = cursor.fetchone() #取的sql查詢結果 conn.close() #關閉鏈接 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 |
User_dal/user_dal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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() #實例化一個對象,將查詢結果逐一添加給對象的屬性 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 ( '查詢結果>>>' ,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回調函數執行的,需要通過用戶唯一的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() #實例化一個對象,將查詢結果逐一添加給對象的屬性 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 #具體執行sql語句的函數 @classmethod def query( cls ,sql,params = None ): result = dal.SQLHelper.fetch_one(sql,params) return result |
denglu.py flask主運行文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
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__) #項目中設置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) '''登錄函數,首先實例化form對象 然后通過form對象驗證post接收到的數據格式是否正確 然后通過login_auth函數,用username與password向數據庫查詢這個用戶,并將狀態碼以及對象返回 判斷狀態碼,如果正確則將對象傳入login_user中,然后就可以跳轉到正確頁面了''' @login_manager .user_loader def load_user( id ): return user_dal.User_Dal.load_user_byid( id ) ''' load_user是一個flask_login的回調函數,在登陸之后,每訪問一個帶Login_required裝飾的視圖函數就要執行一次, 該函數返回一個用戶對象,通過id來用sql語句查到的用戶數據,然后實例化一個對象,并返回。 ''' #登陸成功跳轉的視圖函數 @app .route( '/t' ) @login_required def hello_world(): print ( '登錄跳轉' ) return 'Hello World!' #隨便寫的另一個視圖函數 @app .route( '/b' ) @login_required def hello(): print ( '視圖函數b' ) return 'Hello b!' if __name__ = = '__main__' : app.run() |
簡單總結一下:
通過flask的form表單驗證數據格式
然后通過用戶名密碼從數據庫取用戶對象,將sql執行結果賦值給一個實例化的對象
將這個對象傳給login_user,
然后成功跳轉。
注意要寫一個load_user回調函數嗎,返回的是通過id取到的數據庫并實例化的對象的用戶對象。
這個回調函數每次訪問帶login_required裝飾器的視圖函數都會被執行。
還有一個就是current_user相當于就是實例化的用戶對象,可以取用戶的其他屬性,注意,其他屬性僅限于sql語句查到的字段并添加給實例化對象的屬性。
代碼比較簡單,只是為了實現功能,敬請諒解,如有錯誤歡迎指出。
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/ArmoredTitan/p/8985656.html