赞
踩
BluePrint: (auth.py)
# coding: utf-8
from flask import request, render_template, redirect, Blueprint, url_for
from flask_login import LoginManager, login_user, UserMixin, login_required, current_user
from models.admin import Admin
auth = Blueprint('auth', __name__)
login_manage = LoginManager()
login_manage.login_view = 'auth.login'
def init_auth(app):
"""
运行一次即可,放在初始化文件里运行
:param app: from Flask()
"""
login_manage.init_app(app)
class User(UserMixin):
def __init__(self, user):
self.user = user
def get_id(self):
"""登录成功后,就会调用get_id()获取到id存入session中"""
# 这个demo我直接使用了username做为id
return self.user
@login_manage.user_loader
def load_user(user_id):
"""
每次经过@login_required的地方,本函数都会被调用
:param user_id : 是上面的 User 类中调用 get_id() 获取的
:return 本回调函数要返回一个User对象
"""
# 此Demo因为user_id就是username,所以直接生成类即可
return User(user_id)
@auth.route('/login', methods=['GET', 'POST'])
def login():
err = ''
if request.method == 'POST':
user, pw = request.form.get('user'), request.form.get('pass')
if user and pw and Admin.is_admin(user, pw):
#: 这里登录之后,flask-login的current_user就是当前的User类
login_user(User(user))
return redirect(request.args.get('next'))
else:
err = '账号密码错误'
return render_template('login.html', error=err)
login.html
Login.parent{ text-align: center; width: 100%; height:100%; margin-top:10% }
.child{ display:inline-block; width:300px;height:500px; text-align: center; }
.btn { width:100px; height:25px; margin:3% }
.err { color:red; }
strong { font-size:22px }
dd { margin:10px; }
{{caption}}
登录
{{ error }}
调用:
# coding: utf-8
from flask import Flask, request, render_template
from views.auth import auth, login_required, init_auth, current_user
app = Flask(__name__)
app.secret_key = 'E17Z123-xxxxxxyyy'
app.register_blueprint(auth)
init_auth(app)
@app.route('/start')
@login_required
def start():
return 'START'
@app.route('/test')
@login_required
def test():
return current_user.user
if __name__ == '__main__':
app.run(host='127.0.0.1', port=5000, use_reloader=True)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。