flask-user and flask-admin实现登录验证

前几天一直在想着如何能用flask-user对flask-admin进行登录验证

通过两天的实验达到了目标(由于资料参考比较少所以花的时间多了些)

flask-user  将flask-login整合了进来  因此    实现方式与flask-login有点相识

下面是我的代码

from flask import Flask,url_for
from flask_sqlalchemy import SQLAlchemy
from flask_user  import login_required,UserManager,UserMixin,SQLAlchemyAdapter,current_user

from  flask_migrate import  Migrate,MigrateCommand
from  flask_script import Manager
from  flask_admin.contrib.fileadmin import  FileAdmin
from  flask_admin.base import AdminIndexView,expose
#from  flask_user import  UserManager,SQLAlchemyAdapter,current_user




from  flask_admin import  Admin, form
from  flask_admin.contrib.sqla import  ModelView   #ModelView  模型视图  


app = Flask(__name__)

app.config['SECRET_KEY'] = "thisisasecret"
app.config['SQLALCHEMY_DATABASE_URI']="sqlite:///database.db"
app.config["CSRF_ENABLED"]=True
app.config['USER_ENABLE_EMAIL'] = False
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"]=True
app.config["SQLALCHEMY_COMMIT_TEARDOWN "]= True
db = SQLAlchemy(app)


'''
数据库版本迁移
'''
manager=Manager(app)
migrate = Migrate(app,db)
manager.add_command('db',MigrateCommand)



class User(db.Model,UserMixin):
    id = db.Column(db.Integer , primary_key=True)
    username = db.Column(db.String(50),nullable = False , unique = True)
    password = db.Column(db.String(255),nullable = False ,server_default = '')
    active = db.Column(db.Boolean(),nullable = False,server_default = "0")




db_adapter = SQLAlchemyAdapter(db,User)
user_namager=UserManager(db_adapter,app)

"admin"
admin=Admin(app)  #创建admin对象

#user_namage = UserManager(db_adapter,app)

class MyUserView(ModelView):
    def is_accessible(self):#登录了才能显示,没有登录就不显示
        return current_user.is_authenticated
    def inaccessible_callback(self, name, **kwargs):
        return  url_for("admin")   #登录成功就返回到指定界面






@app.route("/")
def  index():
    return "<h1>this is the home page!</h1>"



@app.route("/profile")
@login_required
def profile():
    return "<h1>this is the protected profile page!</h1>"



admin.add_view(MyUserView(User,db.session))  #添加用户视图

if __name__ == '__main__':
    manager.run(debug =True)

 

 

目录结构

代码上传到github:https://github.com/peichenzhong/flask-user-and-flask-admin

 

运行效果:

未登录前

登录成功后

退出登录:

 

 

 

 

 

 

 

发布了25 篇原创文章 · 获赞 8 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览