如何将 Flask-Admin 与 Flask-Principal 一起使用的简单示例
from functools import partial
from flask.ext.admin import Admin as BaseAdmin, AdminIndexView
from flask.ext.principal import Permission, identity_loaded, Need
from flask.ext.security import current_user
PartnerAccessNeed = partial(Need, 'access')
class PartnerAccessPermission(Permission):
def __init__(self, partner_id):
need = PartnerAccessNeed(partner_id)
super(PartnerAccessPermission, self).__init__(need)
@identity_loaded.connect
def on_post_identity_loaded(sender, identity):
if hasattr(current_user, 'partner'):
identity.provides.add(PartnerAccessNeed(current_user.partner.id))
class PartnerAdminIndexView(AdminIndexView):
def __init__(self, partner_id, *args, **kwargs):
self.partner_id = partner_id
super(PartnerAdminIndexView, self).__init__(*args, **kwargs)
def is_accessible(self):
if current_user.is_anonymous():
return redirect(url_for_security('login'))
if not current_user.is_partner():
return False
permission = PartnerAccessPermission(self.partner_id)
if permission.can():
return True
return False
class PartnerAdmin(BaseAdmin):
def __init__(self, partner_id, endpoint, name, subdomain, *args, **kwargs):
index = PartnerAdminIndexView(name=name,
endpoint=endpoint,
url='/dashboard',
partner_id=partner_id)
super(PartnerAdmin, self).__init__(base_template='mcnm/master.html', index_view=index, subdomain=subdomain)