先加載flask_login
ext.py 在app下的__init__.py 進行引用把,我就不寫了
login_manager = LoginManager() # 如果沒有登錄則重定向到該藍圖的視圖函數 login_manager.login_view = "user.login" # 對登錄用戶進行監視,最高等級 login_manager.session_protection = "strong" def inin_ext(app): login_manager.init_app(app)
然后在數據庫用戶User模型中除了繼承自sqlalhemy之外還繼承 flask_login的 UserMixin
modles.py
''' 模型類需要繼承flask_login UserMixin ,不然需要重寫四個方法 is_active get_id is_authenticated 登錄用戶 is_anonymous 未登錄用戶 只需需要理會這兩個方法就行 ''' class User(db.Model,UserMixin): id = db.Column(db.Integer,primary_key=True,autoincrement=True) nicheng = db.Column(db.String(20)) email = db.Column(db.String(20)) password_hash = db.Column(db.String(200)) # 以下都是關於密碼加密解密 @property def password(self): raise AttributeError('沒有權限查看密碼!') @password.setter def password(self,password): self.password_hash = generate_password_hash(password) def check_password(self,password): return check_password_hash(self.password_hash,password)
繼續在該模型文件中添加 用來獲取傳遞過來的實例
# flask_login的實例 + user_loader 獲取在視圖函數views.py中login_user傳遞過來的參數 得到該實例 @login_manager.user_loader def load_user(id): return User.query.get(int(id))
views.py
@user.route('/login/',methods=['GET','POST']) def login(): form = loginForm() if form.validate_on_submit(): email = form.email.data password = form.password.data # 每一偶在表單中驗證密碼了,直接在這里驗證是否為True user = User.query.filter_by(email=email).first() if user is not None and user.check_password(password): # 傳入該登錄用戶的User對象,在modles.py中回調函數會對傳入的對象 存入session login_user(user,remember=True) return redirect(url_for('user.index')) return redirect(url_for('user.login')) form.password.data = '' return render_template('login.html',form=form) # 用戶退出 @user.route('/logout') def logout(): logout_user() return redirect(url_for("user.index"))
其實只需要記住 在模型中繼承flask_login UserMixin 並在模型外添加一個獲取用戶實例的函數
@login_manager.user_loader def load_user(id): return User.query.get(int(id))
在進行登錄時 將登錄用戶在數據庫中查詢得到的實例傳遞過去
login_user(user,remember=True) # user 是登錄用戶實例
退出登錄則使用
logout_user()
保護識圖不被未登錄用戶訪問
在每個識圖裝飾器下添加
@藍圖.route('/xxxx/') @login_required def xxxx(): xxxx retrue 'xxxx'
login_manager.login_view = "user.login" # 該配置會將未登錄用戶重定向到該識圖函數中
其中flask 自帶一個 current_app 作為代理對不能導入app實例 進行一個替代 (導入死循環)
flask_login 也帶有一個 current_user 可以對當前登錄用戶進行一個操作,比如數據庫模型有id name ,可以對其操作 current_user.name 得到該實例的數據
特別是在jijia2 模板中操作
{% if not current_user.is_authenticated %} <li><a href="{{ url_for("user.login") }}">登錄</a></li> <li><a href="{{ url_for("user.register") }}">注冊</a></li> {% endif %} {% if current_user.is_authenticated %} <li><a href="{{ url_for("user.index") }}">{{ current_user.nicheng }}</a></li> <li><a href="{{ url_for('user.logout') }}">退出</a></li> {% endif %}
通過 current_user.is_authenticated 對用戶登錄狀態進行一個確定是否為登錄用戶 current_user.nicheng 顯示出該實例用戶的昵稱
在登錄視圖函數中添加session的過期時間,不能再配置文件中填寫,要在登錄時進行書寫
login_user(user)
# 設置session過期時間 過期時間一天
session.permanent = True
app = current_app._get_current_object()
app.permanent_session_lifetime = timedelta(days=1)
詳細請看 https://www.cnblogs.com/practice-h/p/8883487.html
