Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save a4amaan/b191b50d781ba97276c4cbb150bc11a5 to your computer and use it in GitHub Desktop.
Save a4amaan/b191b50d781ba97276c4cbb150bc11a5 to your computer and use it in GitHub Desktop.
flask-admin with flask-basicauth login example(Flask-BasicAuth简单登录Flask-admin后台)
#!/usr/bin/python
# -*- coding: utf-8 -*-
# flask related modules
from flask import Flask, Response
from flask_basicauth import BasicAuth
from flask_admin import Admin
from flask_admin.contrib import sqla
from werkzeug.exceptions import HTTPException
# database set up
from sqlalchemy import Column, String, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
engine = create_engine('sqlite:///thing.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()
# create a Thing object to database
# 建立一个包含对象Thing的数据库,保存到根目录的thing.db
class Thing(Base):
__tablename__ = 'thing'
id = Column(Integer, primary_key=True)
item1 = Column(String(10))
item2 = Column(String(20))
Base.metadata.create_all(engine)
# build flask app
# 创建flask app
app = Flask(__name__)
# set admin username and password
# 设置admin用户名和密码
app.config['BASIC_AUTH_USERNAME'] = 'username'
app.config['BASIC_AUTH_PASSWORD'] = 'password'
# add flask-basicauth to flask app
# 引入flask-basicauth
basic_auth = BasicAuth(app)
# login failed handler, from:
# https://computableverse.com/blog/flask-admin-using-basicauth
# 登录失败控制器,来源:
# https://computableverse.com/blog/flask-admin-using-basicauth
class AuthException(HTTPException):
def __init__(self, message):
# python 2
super(AuthException, self).__init__(message, Response(
message, 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
))
# # python 3
# super().__init__(message, Response(
# message, 401,
# {'WWW-Authenticate': 'Basic realm="Login Required"'}
# ))
# overwrite ModelView of flask_admin to just affects admin page
# 重写flask-admin登录类
class ModelView(sqla.ModelView):
def is_accessible(self):
if not basic_auth.authenticate():
raise AuthException('Not authenticated. Refresh the page.')
else:
return True
def inaccessible_callback(self, name, **kwargs):
return redirect(basic_auth.challenge())
# flask-admin config
# flask-admin 基础配置
admin = Admin(app, name='Admin Panel', template_mode='bootstrap3')
admin.add_view(ModelView(Thing, session))
# logout
# 退出页面
@app.route('/logout')
def Logout():
raise AuthException('Successfully logged out.')
# index page
# 首页
@app.route('/')
@app.route('/index')
def index():
return 'This is index page'
# start app at localhost:8000
# 运行app: localhost:8000
if __name__ == '__main__':
app.secret_key = 'superdevkey'
app.debug = True
app.run(host='0.0.0.0', port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment