溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Flask-admin 使用總結(jié)

發(fā)布時(shí)間:2020-07-15 22:07:02 來(lái)源:網(wǎng)絡(luò) 閱讀:2658 作者:wenguonideshou 欄目:開(kāi)發(fā)技術(shù)
ModelView    表管理,進(jìn)入權(quán)限
BaseView,expose  自定義視圖
AdminIndexView  進(jìn)入權(quán)限
FileAdmin   文件管理
from flask_admin import Admin
from flask_admin.contrib.fileadmin import FileAdmin
from flask_admin import Admin, expose, BaseView
from flask_admin.contrib.sqla import ModelView
#flask-admin國(guó)際化多語(yǔ)言
from flask_babelex import Babel
app = Flask(__name__)
babel = Babel(app)
app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN'
# 初始化admin后臺(tái)
admin = Admin(app, name='env manager')
# 也可對(duì)后臺(tái)首頁(yè)進(jìn)行自定義
# 后臺(tái)標(biāo)題修改為"導(dǎo)航欄",主頁(yè)設(shè)置為welcome.html,后臺(tái)url也修改
admin = Admin(app,index_view=AdminIndexView(name='導(dǎo)航欄',template='welcome.html',url='/admin'))
# 或如下,其中MyAdminIndexView()繼承AdminIndexView()
admin = Admin(app,name='管理中心',index_view=MyAdminIndexView(),base_template='admin/my_master.html')
# 定義后臺(tái)對(duì)表可增加、可編輯、可導(dǎo)出,可搜索,只顯示指定的列
class HashView(ModelView):
    create_modal = True
    edit_modal = True
    can_export = True
    column_searchable_list = ['title']
column_list = ('id', 'title','timestamp','count','content'')
    column_labels = {
        'id':'序號(hào)',
        'title' : '新聞標(biāo)題',
        'timestamp':'發(fā)布時(shí)間',
        'count':'瀏覽次數(shù)',
        'content':'新聞內(nèi)容'
    }
#或者下面這種寫(xiě)法
column_labels = dict(
	username='用戶(hù)名',
	)
#不顯示指定的列
	column_exclude_list = (
	'password_hash',
	)
# 自定義視圖
# 每個(gè)自定義視圖必須提供一個(gè)@expose('/') 的index方法,否則會(huì)報(bào)錯(cuò)
class UserView(BaseView):
@expose('/')
def index(self):
return self.render('admin/user.html')
@expose('/user_manager')
def user_manager(self):
return self.render('admin/user.html')
class MyNews(BaseView):
    @expose('/', methods=['GET', 'POST'])    def index(self):
        form = NameForm()        return self.render('postnews.html', form=form)
#postnews.html在templates目錄下
# 添加表管理、自定義視圖
admin.add_view(HashView(User, db.session, name='用戶(hù)'))
admin.add_view(HashView(Role, db.session, name='角色'))
admin.add_view(HashView(Env, db.session, name='環(huán)境配置'))
admin.add_view(UserView(name='user_manager'))
admin.add_view(MyNews(name=u'發(fā)表新聞'))
# category是可選的目錄,且會(huì)自動(dòng)添加上去admin.add_view(UserView(User, db.session, name='信息', category='用戶(hù)管理'))
# 添加文件管理
admin.add_view(FileAdmin(config_path, '/file/', name='Config Files'))
用Flask-Login做身份驗(yàn)證
修改templates下的模板文件index.html,實(shí)現(xiàn)管理員登錄帶有CSRF 令牌的安全表單
{% extends 'admin/master.html' %}
{% block body %}
{{ super() }}
{% if current_user.is_authenticated %}
歡迎來(lái)到后臺(tái)管理系統(tǒng)!
{% else %}
{{ form.hidden_tag() if form.hidden_tag }}
{% for f in form if f.type != 'CSRFTokenField' %}
{{ f.label }}
{{ f }}
{% if f.errors %}
{% for e in f.errors %}
{{ e }}
{% endfor %}
{% endif %}
{% endfor %}
登陸
{{ link | safe }}
{% endif %}
{% endblock body %}
定義登錄表單
from wtforms import fields, validators class
LoginForm(FlaskForm): 
login = fields.StringField(label='管理員賬號(hào)', validators=[validators.required()]) 
password = fields.PasswordField(label='密碼', validators=[validators.required()]) 
def validate_login(self, field): 
    user = self.get_user() 
    if user is None: 
        raise validators.ValidationError('賬號(hào)不存在') 
#密碼不能明文存儲(chǔ),用sha256_crypt加密
    if not sha256_crypt.verify(self.password.data, user.password): 
        raise validators.ValidationError('密碼錯(cuò)誤') 
def get_user(self): 
#AdminUser是存儲(chǔ)管理員用戶(hù)密碼的表
    return db.session.query(AdminUser).filter_by(login=self.login.data).first()
#安裝flask-login
pip install flask-login
#初始化,調(diào)用init_login()函數(shù)
from flask_login import current_user, login_user, logout_user, LoginManager
def init_login():
    login_manager = LoginManager()
    login_manager.init_app(app)
@login_manager.user_loader
def load_user(user_id):
    return db.session.query(AdminUser).get(user_id)
#然后在需要管理員權(quán)限的才能看到的視圖中添加代碼
#決定身份驗(yàn)證可見(jiàn)def is_accessible(self):
    return current_user.is_authenticated
圖片上傳
#假設(shè)pics為需要上傳圖片的字段
import os.path as op
def thumb_name(filename):
    name, _ = op.splitext(filename)
    return secure_filename('%s-thumb.jpg' % name)
class MyForm(BaseForm):
    upload = ImageUploadField('File', thumbgen=prefix_name)
import os.path as op
form_extra_fields = {
'pics': upload.ImageUploadField(label='圖片',base_path=file_path),
}
可以使用url_for附帶一個(gè).前綴來(lái)獲得局部視圖的URL:
from flask import url_for
class MyView(BaseView):
    @expose('/')
    def index(self)
        # Get URL for the test view method
        url = url_for('.test')
        return self.render('index.html', url=url)
    @expose('/test/')
    def test(self):
        return self.render('test.html')
建立只允許使用預(yù)定義值的名為status的列的表單:
from wtforms.fields import SelectField
class MyView(ModelView):
    form_overrides = dict(status=SelectField)
    form_args = dict(
        # Pass the choices to the `SelectField`
        status=dict(
            choices=[(0, 'waiting'), (1, 'in_progress'), (2, 'finished')]
        ))
#添加redis控制臺(tái)
from flask_admin.contrib import rediscli
admin.add_view(rediscli.RedisCli(Redis()))
可擴(kuò)展的模板:對(duì)應(yīng)繼承 列表、創(chuàng)建、編輯頁(yè)
admin/model/list.html
admin/model/create.html
admin/model/edit.html
例如:
{% extends 'admin/model/edit.html' %}
{% block body %}
MicroBlog Edit View
{{ super() }}
{% endblock %}
使視圖使用模板
class MicroBlogModelView(ModelView):
    edit_template = 'microblog_edit.html'
    # create_template = 'microblog_create.html'
    # list_template = 'microblog_list.html'
如果使用基礎(chǔ)模板,則在基礎(chǔ)函數(shù)中添加
admin = Admin(app, base_template='microblog_master.html')
防止csrf***保護(hù)
#指定form_base_class 參數(shù)
from flask_admin.form import SecureForm
from flask_admin.contrib.sqla import ModelView
class CarAdmin(ModelView):
    form_base_class = SecureForm


向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI