User login management for the Flask framework's study guide

  • 2020-05-17 05:51:29
  • OfStack

Continue the learning journey of flask. Today, we will introduce the login management module of flask. Do you still remember the small project of blog in the last article? Login is the verification code we wrote ourselves, and there are probably the following steps:

1. Enter the user name and password in the login box

2. The flask view function obtains the user password, and then queries the user information in the database for matching

3. If successful, write to session and redirect to the home page

4. If you must log in to access a particular view, verify the presence of the user in session in each view function.

Today, we continue to transform the blog project. The flask-login module introduced is to solve these common functions with less business correlation for us. It can help us:

ID allows you to log in and out freely by storing active users in your session.
Allows you to restrict logins (or logouts) to views that users can access.
Handle the tricky "remember me" feature.
Helps you protect user sessions from being compromised by cookie.
It can be integrated with Flask-Principal or other authentication extensions that may be used later.

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) at /blog2/ s 51en__.py add:


# Reference the package 
from flask.ext.login import LoginManager

# Land management 
# The statement login object 
login_manager = LoginManager()
# Initialize the binding to the application 
login_manager.init_app(app)

# Declare the default view function as login When we proceed @require_login If not logged in will automatically jump to the view function processing 
login_manager.login_view = "login"

# When the login is successful, the function automatically stores the user from the session  ID  Reload the user object. It should accept 1 A user's  unicode ID  As a parameter and returns the corresponding user object. 
@login_manager.user_loader
def load_user(userid):
return User.query.get(int(userid))

2.2) modify the User model (the red part is the new code)


from flask.ext.login import UserMixin

from blog2 import db

class 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 '<User %r>' % self.username

The user class must implement the following methods:

is_authenticated

True is returned when the user is authenticated, that is, when valid proof is provided (only authenticated users will satisfy the condition of login_required).

is_active

If this is an active user and has been verified, the account has been activated, has not been deactivated, and does not meet any of the criteria for your application to reject an account, return True. Inactive accounts may not be logged in (without being forced, of course).

is_anonymous

If it is an anonymous user, return True. (real users should return False.)

get_id()

Returns an unicode that identifies the user only by 1 and can be used to load the user from the user_loader callback. Note that it has to be 1 unicode - if ID was originally 1 int or some other type, you need to convert it to unicode.
To implement user classes easily, you can inherit from UserMixin, which provides a default implementation for all of these methods. We use the UserMixin implementation here.

2.3) modify view function (the red part is new)


from flask.ext.login import login_required, login_user, logout_user

from blog2.model.User import User
from blog2.model.Category import Category
import os

from blog2 import app,db
from flask import request,render_template,flash,abort,url_for,redirect,session,Flask,g

@app.route('/')
@login_required
def show_entries():
  categorys = Category.query.all()
  return render_template('show_entries.html',entries=categorys)

@app.route('/add',methods=['POST'])
@login_required
def add_entry():
  # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
  #  The first 1 Version login mode 
  # 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 1 Version login mode 
    # 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_required
def logout():
  # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --  
  #  The first 1 Version logout mode 
  # session.pop('logged_in', None)
  # -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --  
   logout_user()
  flash('You were logged out')
  return redirect(url_for('show_entries'))

Manage login through flask-login, the code is very simple:

login_required: this decorator will be placed on the views that need to be logged in to access. If there are no views with login restrictions, it will jump to the login page, controlled by login_manager.login_view = "login"
login_user(user) : pass in 1 user object for login verification, return true correctly, otherwise return false
logout_user() : logout function to clear user information in session

2.4) the user is referenced in the template


{% if current_user.is_authenticated() %}
 Hi {{ current_user.name }}!
{% endif %}

Change the previous layout.html and show_entries.html templates to flask-login:

{% if not current_user.is_authenticated() %}

current_user value: when the user is not logged in, the value is < flask_login.AnonymousUserMixin object at 0x0000000003DCF550 > , or anonymous users
After the user logs in, the value is < User u'admin' >

Of course, user login can also be customized according to the actual situation, the specific is not detailed in 11.

[reference]

Flask - Login Chinese version: http: / / www pythondoc. com/flask - login / # id1
Flask - Login English version: http: / / flask - login readthedocs. io/en latest /


Related articles: