Flask-Authorize 0.2.2
pip install Flask-Authorize
上次发布日期:
用于内容授权和访问控制的烧瓶插件
- 您所在的位置:
- Python中文网 >
- pypi >
- Flask-Authorize库 >
- 正文
Flask-Authorize的Python项目详细描述
烧瓶授权
Flask Authorize是一个Flask扩展,旨在简化将访问控制列表(acl)和基于角色的访问控制(RBAC)合并到包含敏感数据的应用程序中的过程,允许开发人员将注意力集中在应用程序的实际代码上,而不是执行权限的逻辑。它使用类unix的权限方案来强制对现有内容的访问权限,还提供了在整个应用程序中全局强制执行权限的机制。在
安装
要通过pip安装最新的稳定版本,请运行:
$ pip install Flask-Authorize
或者使用easy_install,运行:
^{pr2}$要安装项目的最新版本(不推荐):
$ git clone http://github.com/bprinty/Flask-Authorize.git
$ cd Flask-Authorize
$ python setup.py install
用法
下面详细介绍了一个演示如何使用扩展的最小示例。首先,要设置带扩展的烧瓶应用程序:
fromflaskimportFlaskfromflask_loginimportLoginManagerfromflask_sqlalchemyimportSQLAlchemyapp=Flask(__name__)app.config.from_object(Config)db=SQLAlchemy(app)login=LoginManager(app)authorize=Authorize(app)
定义数据库模型:
fromflask_authorizeimportRestrictionsMixin,AllowancesMixinfromflask_authorizeimportPermissionsMixin# mapping tablesUserGroup=db.Table('user_group',db.Model.metadata,db.Column('user_id',db.Integer,db.ForeignKey('users.id')),db.Column('group_id',db.Integer,db.ForeignKey('groups.id')))UserRole=db.Table('user_role',db.Model.metadata,db.Column('user_id',db.Integer,db.ForeignKey('users.id')),db.Column('role_id',db.Integer,db.ForeignKey('roles.id')))# modelsclassUser(db.Model):__tablename__='users'id=db.Column(db.Integer,primary_key=True)name=db.Column(db.String(255),nullable=False,unique=True)# `roles` and `groups` are reserved words that *must* be defined# on the `User` model to use group- or role-based authorization.roles=db.relationship('Role',secondary=UserRole)groups=db.relationship('Group',secondary=UserGroup)classGroup(db.Model,RestrictionsMixin):id=db.Column(db.Integer,primary_key=True)name=db.Column(db.String(255),nullable=False,unique=True)classRole(db.Model,AllowancesMixin):id=db.Column(db.Integer,primary_key=True)name=db.Column(db.String(255),nullable=False,unique=True)classArticle(db.Model,PermissionsMixin):__tablename__='articles'__permissions__=dict(owner=['read','update','delete','revoke'],group=['read','update'],other=['read'])id=db.Column(db.Integer,primary_key=True)name=db.Column(db.String(255),index=True,nullable=False)
定义终结点操作:
fromflaskimportjsonifyfromwerkzeugimportNotFound,Unauthorized@app.route('/articles',methods=['POST'])@login.logged_in@authorize.create(Article)defarticle():article=Article(**request.json)db.session.add(article)db.session.commit()returnjsonify(msg='Created Article'),200@app.route('/articles/<int:ident>',methods=['GET','PUT','DELETE'])@login.logged_indefsingle_article(ident):article=db.session.query(Article).filter_by(id=ident).first()ifnotarticle:raiseNotFoundifrequest.method=='GET':# check if the current user is authorized to read the articleifnotauthorize.read(article):raiseUnauthorizedreturnjsonify(id=article.id,name=article.name),200elifrequest.method=='PUT':# check if the current user is authorized to update to the articleifnotauthorize.update(article):raiseUnauthorizedforkey,valueinrequest.json.items():setattr(article,key,value)db.session.commit()returnjsonify(id=article.id,name=article.name),200elifrequest.method=='DELETE':# check if the current user is associated with the 'admin' roleifnotauthorize.delete(article)or \ notauthorize.has_role('admin'):raiseUnauthorizeddb.session.delete(article)db.session.commit()return@app.route('/articles/<int:ident>/revoke',methods=['POST'])@login.logged_indefrevoke_article(ident):article=db.session.query(Article).filter_by(id=ident).first()ifnotarticle:raiseNotFound# check if the current user can revoke the articleifnotauthorize.revoke(article):raiseUnauthorizedarticle.revoked=Truedb.session.commit()return
此外,如果已将应用程序配置为将请求处理分派给API函数,则可以使用authorize扩展对象作为装饰符:
@authorize.create(Article)defcreate_article(name):article=Article(**request.json)db.session.add(article)db.session.commit()returnarticle@authorize.readdefread_article(article):returnarticle@authorize.updatedefupdate_article(article,**kwargs):forkey,valueinrequest.json.items():setattr(article,key,value)db.session.commit()returnarticle@authorize.deletedefdelete_article(article):db.session.delete(article)return@authorize.revokedefrevoke_article(article):article.revoke=Truedb.session.commit()return@authorize.has_role('admin')defget_admin_articles():pass
使用扩展作为装饰器可以在很大程度上消除与权限检查相关的样板文件。另外,使用authorizeextension对象作为装饰符将隐式检查当前用户对函数的每个参数或关键字参数的访问。例如,如果您的方法接受两个Article对象并将它们合并为一个对象,则可以为这两个操作添加权限,如下所示:
@authorize.read@authorize.create(Article)defmerge_articles(article1,article2):new_article=Article(name=article1.name+article.2.name)db.session.add(new_article)db.session.delete(article1,article2)db.session.commit()returnnew_article
此函数将确保当前用户对这两个文章都具有读取权限,并且还可以对Article模型本身创建权限。如果不满足授权条件,将抛出Unauthorized错误。在
最后,authorize运算符也可以在Jinja模板中使用:
<!-- button for creating new article --> {% if authorize.create('articles') %} <button>Create Article</button> {% endif %} <!-- display article feed --> {% for article in articles %} <!-- show article if user has read access --> {% if authorize.read(article) %} <h1>{{ article.name }}</h1><!-- add edit button for users who can update--> {% if authorize.update(article) %} <button>Update Article</button> {% endif %} <!-- add delete button for administrators --> {% if authorize.in_group('admins') %} <button>Delete Article</button> {% endif %} {% endif %} {% endfor %}
文档
有关更详细的文档,请参阅Docs。在
问题/eh3>
在GitHub issue tracker中提交问题。在
- 项目
标签:
推荐PyPI第三方库
marshmallow-nump
棉花糖纽姆地
mypy-boto3-codedeplo
由mypyboto3buider4.2.0生成的boto3.codedeploy1.16.35服务的类型注释
streamer
直接从torrent流式播放电影,无需下载
ZLLR
ZLLRP协议
py3-infobip
infobip服务的python3客户端
itemset-mining
用于项集挖掘算法的python包。
rasa-plus
rasa机器人对话框的管理器
obsah
ansible包装
cortado
在纯Python中实现超快速XGBoost的高性能ML库
taowa5
/
koreanbots
一个简单的pythonapi包装器。
motion-imitation
使用osqp解算器的MPC的python绑定运动仿真和MPC
gen-py-module
生成PY模块
odoo11-addon-stock-inventory-virtual-location
允许更改库存调整中的虚拟位置。
passhashdb
建立和搜索密码哈希数据库
导 航 栏
项目 链接
标 签
许可证: BSD许可证(BSD 3条款)
作者信息:: 暂无
维护者
bprinty最新PyPI项目
- italian_vip_says
- UFx
- vofs
- fake_item_generator
- NerEva
- django-monologue
- fio_product_attribute_strict
- climailsystem
- pyshape
- tbb-devel
- npy-append-arra
- anthill.tal.macrorenderer
- odoo11-addon-stock-a
- uuuu
- contextil
- fyl_nester
- appomatic_renderable
- teacher
- chuletas
- slackbot_ce
最新Python常见问题
- VirtualEnvRapper错误:路径python2(来自python=python2)不存在
- virtualenvs上的pyinstaller,没有名为导入错误的模块
- virtualenvs是否可以退回到用户包而不是系统包?
- virtualenvwrapper CentOS7
- virtualenvwrapper IOError:[Errno 13]权限被拒绝
- virtualenvwrapper mkproject和shell在windows中的启动问题?
- virtualenvwrapper mkvirtualenv不工作但没有错误
- Virtualenvwrapper python bash
- virtualenvwrapper:“workon”何时更改到项目目录?
- virtualenvwrapper:mkvirtualenv可以工作,但是rmvirtualenv返回bash:没有这样的文件或目录
- virtualenvwrapper:virtualenv信息存储在哪里?
- virtualenvwrapper:命令“python设置.pyegg_info“失败,错误代码为1
- virtualenvwrapper:如何将mkvirtualenv的默认Python版本/路径更改为ins
- Virtualenvwrapper:模块“pkg_resources”没有属性“iter_entry_points”
- Virtualenvwrapper:没有名为virtualenvwrapp的模块