Home  >  Article  >  Backend Development  >  Flask framework study guide user login management

Flask framework study guide user login management

WBOY
WBOYOriginal
2016-12-05 13:27:221512browse

Continue the flask learning journey. Today I will introduce the login management module of flask. Do you still remember the small blog project in the previous article? The login is a verification code written by ourselves. It probably has the following steps:

1. Enter your username 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 it into the session and redirect to the homepage

4. If you must log in to access a specific view, then you need to verify whether the user exists in the session in each view function.

Today we continue to transform the blog project. The flask-login module introduced is to help us handle these public functions that are less business-related. It can help us:

Store the currently active user ID in the session, allowing you to log in and out freely.
Allows you to limit the views that logged in (or logged out) users can access.
Dealing with the tricky "remember me" feature.
Helps you protect user sessions from cookie theft.
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:workdirdct-server-5055187src>pip install flask-login

2. Use flask-login

2.1) Add in /blog2/__init__.py:

#引用包
from flask.ext.login import LoginManager

#登陆管理
#声明login对象
login_manager = LoginManager()
#初始化绑定到应用
login_manager.init_app(app)

#声明默认视图函数为login,当我们进行@require_login时,如果没登陆会自动跳到该视图函数处理
login_manager.login_view = "login"

#当登陆成功后,该函数会自动从会话中存储的用户 ID 重新加载用户对象。它应该接受一个用户的 unicode ID 作为参数,并且返回相应的用户对象。
@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 '' % self.username

The user class must implement the following methods:

is_authenticated

Return True when the user is authenticated, that is, when a valid proof is provided (only authenticated users will meet the login_required condition.)

is_active

If this is an active user and has been verified, the account is activated, not deactivated, and does not meet any of your application's conditions for rejecting an account, return True . Inactive accounts may not be logged in (unless forced to do so, of course).

is_anonymous

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

get_id()

Returns a unicode that uniquely identifies the user and can be used to load the user from the user_loader callback. Note that must be a unicode - if the ID is originally 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 of all these methods. We use UserMixin to implement it here.

2.3) Modify the 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():
  #——————————————————————————————————————————————
  # 第一版登陆方式
  # 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()
    #——————————————————————————————————————————————————————————————————————————
    #第一版登陆方式
    # 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():
  #—————————————————————————————————————————————— 
  # 第一版登出方式
  # 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 and simple:

@login_required: This decorator is placed on the view that requires login to access. If there is no login to access the restricted view, it will jump to the login page, controlled by login_manager.login_view = "login" in __init__.py
login_user(user): Pass in a user object for login verification, return true if correct, otherwise return false
logout_user(): Logout function, clear user information in the session

2.4) Reference users in templates

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

Change the method of determining whether the user is logged in in the previous layout.html and show_entries.html templates to the method in flask-login:

{% if not current_user.is_authenticated() %}

current_user value: When the user is not logged in, the value is 5d2cfcc3b350ac1a97f856c2fa5fd2b2, which is an anonymous user
After the user logs in, the value is 97380c8f5e24dafe948d47dc8d6d6a44

Of course, user login can also be customized according to the actual situation, and the details will not be detailed one by one.

【Reference Document】

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn