This is the third article in The Flask framework's Learning Guide series. it mainly tells you how to create the flask login management module. if you have any need, refer to continue the flask learning journey. Today we will introduce the flask login management module. do you still remember the blog project we wrote in the previous article? the login verification code is as follows:
1. enter the user name and password in the logon box.
2. the flask view function obtains the user password and then queries the user information in the database for matching.
3. if it succeeds, it will be written into the session and redirected to the homepage.
4. if you have to log on to a specific view to access the view, you need to verify the existence of the user in each View function session.
The flask-login module introduced in the blog project is to solve these public functions with less relevance for us. it can help us:
Store active user IDs in sessions so that you can log on and log out freely.
Allows you to restrict the views that can be accessed by login (or logout) users.
Handle the tricky "Remember Me" feature.
This helps you protect user sessions from cookie theft.
It can be integrated with Flask-Principal or other authentication extensions that may be used in the future.
1. how to use the flask-login module?
1. install flask-login
E:\workdir\dct-server-5055187\src>pip install flask-login
2. use flask-login
2.1) in/blog2/_ init _. py, add:
# Reference package from flask. ext. login import LoginManager # login management # declare the login object login_manager = LoginManager () # initialize and bind to the application login_manager.init_app (app) # declare that the default view function is login. when @ require_login is performed, if login_manager.login_view = "login" is not logged in, the function automatically jumps to this view to process login_manager.login_view = "login" # After successful login, the function automatically reloads the user object from the user ID stored in the session. It should take a user's unicode ID as the parameter and return the corresponding user object. @ Login_manager.user_loaderdef load_user (userid): return User. query. get (int (userid ))
2.2) modify the User model (add code in red)
from flask.ext.login import UserMixinfrom blog2 import dbclass User(db.Model, UserMixin): __tablename__ = 'b_user' id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(10),unique=True) password = db.Column(db.String(16)) def __init__(self,username,password): self.username = username self.password = password def __repr__(self): return '
' % self.username
This user class must implement the following methods:
is_authenticated
True is returned when the user passes the verification, that is, a valid proof is provided (only the authenticated user meets the conditions of login_required .)
is_active
If this is an active user and the account has been verified, the account has been activated, disabled, and does not meet any conditions for your application to reject an account, True is returned. Non-active accounts may not log in (of course, they are not forced ).
is_anonymous
Returns True if it is an anonymous user. (False should be returned for real users .)
get_id()
Returns a unicode that uniquely identifies a user and can be used to load the user's unicode from the user_loader callback. Note that it must be a unicode -- if the ID is an int or other type, you need to convert it to unicode.
To easily implement user classes, you can inherit from UserMixin, which provides default implementations for all these methods. Here we use UserMixin.
2.3) modify the view function (the red part is new)
From flask. ext. login import login_required, login_user, logout_userfrom blog2.model. user import Userfrom blog2.model. category import Categoryimport osfrom blog2 import app, dbfrom flask import request, render_template, flash, abort, url_for, redirect, session, Flask, g@app.route ('/') @ login_requireddef show_entries (): categorys = Category. query. all () return render_template('show_entries.html ', entries = categorys) @ app. route ('/add', methods = ['post']) @ login_requireddef add_entry (): # ------------------------------------------ # First-version login method # if not session. get ('logged _ in'): # abort (401) # ------------------------------------------------ title = request. form ['title'] content = request. form ['text'] category = Category (title, content) db. session. add (category) db. session. commit () flash ('new entry was successfully posted') return redirect (url_for ('show _ entries') @ app. route ('/login', methods = ['GET', 'post']) def login (): error = None if request. method = 'Post': user = User. query. filter_by (username = request. form ['username']). first () # -------------------------------------------------------------------------- # The first login method # passwd = User. query. filter_by (password = request. form ['password']). first () # if user is None: # error = 'invalid username' # elif passwd is None: # error = 'invalid password' # else: # session ['logged _ in'] = True # flash ('you were logged in') # return redirect (url_for ('show _ entries') # -------------------------------------------------------------------------- login_user (user) flash ('logged in successfully. ') return redirect (url_for ('show _ entries') return render_template('login.html ', error = error) @ app. route ('/logout') @ login_requireddef logout (): # -------------------------------------------- # The first logout mode # session. pop ('logger _ in', None) # -------------------------------------------------- logout_user () flash ('you were logged out') return redirect (url_for ('show _ entries '))
Using flask-login to manage login, the code is very simple and simple:
@ Login_required __. login_manager.login_view = "login" control in py
Login_user (user): input a user object for login verification. true is returned correctly; otherwise, false is returned.
Logout_user (): log out of the function and clear the user information in the session.
2.4) reference users in the template
{% if current_user.is_authenticated() %} Hi {{ current_user.name }}!{% endif %}
Change the layout.html and show_entries.html templates to the flask-login method:
{% if not current_user.is_authenticated() %}
Current_user value: the value is That is, anonymous users
The value is
Of course, user login can also be customized based on the actual situation, which is not described in detail.
[Reference]
Flask-Login Chinese version: http://www.pythondoc.com/flask-login/#id1
Flask-Login English version: http://flask-login.readthedocs.io/en/latest/