flask-login2的简单使用
1 #coding:utf8 2 from flask import Flask, render_template, request, redirect, url_for, flash, abort 3 from flask_login import (LoginManager, UserMixin, login_user, logout_user, 4 current_user, login_required, fresh_login_required) 5 6 app = Flask(__name__) 7 login_manager = LoginManager(app) 8 # 设置登录视图的名称,如果一个未登录用户请求一个只有登录用户才能访问的视图, 9 # 则闪现一条错误消息,并重定向到这里设置的登录视图。 10 # 如果未设置登录视图,则直接返回401错误。 11 login_manager.login_view = 'login' 12 # 设置当未登录用户请求一个只有登录用户才能访问的视图时,闪现的错误消息的内容, 13 # 默认的错误消息是:Please log in to access this page.。 14 login_manager.login_message = 'Unauthorized User' 15 # 设置闪现的错误消息的类别 16 login_manager.login_message_category = "info" 17 18 users = [ 19 {'username': 'Tom', 'password': '111111'}, 20 {'username': 'Michael', 'password': '123456'} 21 ] 22 23 class User(UserMixin): 24 pass 25 26 # 通过用户名,获取用户记录,如果不存在,则返回None 27 def query_user(username): 28 for user in users: 29 if user['username'] == username: 30 return user 31 32 # 如果用户名存在则构建一个新的用户类对象,并使用用户名作为ID 33 # 如果不存在,必须返回None 34 @login_manager.user_loader 35 def load_user(username): 36 if query_user(username) is not None: 37 curr_user = User() 38 curr_user.id = username 39 return curr_user 40 # Must return None if username not found 41 42 # 从请求参数中获取Token,如果Token所对应的用户存在则构建一个新的用户类对象 43 # 并使用用户名作为ID,如果不存在,必须返回None 44 # @login_manager.request_loader 45 # username = request.args.get('token') 46 # user = query_user(username) 47 # if user is not None: 48 # curr_user = User() 49 # curr_user.id = username 50 # return curr_user 51 # # Must return None if username not found 52 53 @login_manager.unauthorized_handler 54 def unauthorized_handler(): 55 return 'Unauthorized' 56 57 @app.route('/') 58 @login_required 59 def index(): 60 return render_template('hello.html') 61 62 @app.route('/home') 63 @fresh_login_required 64 def home(): 65 return 'Logged in as: %s' % current_user.get_id() 66 67 @app.route('/login', methods=['GET', 'POST']) 68 def login(): 69 if request.method == 'POST': 70 username = request.form.get('username') 71 user = query_user(username) 72 # 验证表单中提交的用户名和密码 73 if user is not None and request.form['password'] == user['password']: 74 curr_user = User() 75 curr_user.id = username 76 77 # 通过Flask-Login的login_user方法登录用户 78 login_user(curr_user, remember=True) 79 80 # 如果请求中有next参数,则重定向到其指定的地址, 81 # 没有next参数,则重定向到"index"视图 82 next = request.args.get('next') 83 return redirect(next or url_for('index')) 84 85 flash('Wrong username or password!') 86 # GET 请求 87 return render_template('login.html') 88 89 @app.route('/logout') 90 @login_required 91 def logout(): 92 logout_user() 93 return 'Logged out successfully!' 94 95 app.secret_key = '1234567' 96 97 if __name__ == '__main__': 98 app.run(host='0.0.0.0', debug=True)
http://www.bjhee.com/flask-ext8.html
中文文档:http://docs.jinkan.org/docs/flask-login/