Package: rules
rulesis a tiny but powerful app providing object-level permissions to
Django, without requiring a database. At its core, it is a generic framework
for building rule-based systems, similar todecision trees. It can also be
used as a standalone library in other contexts and frameworks.Featuresruleshas got you covered.rulesis:Documented,tested,reliableandeasy to use.Versatile. Decorate callables to build complex graphs of predicates.
Predicates can be any type of callable – simple functions, lambdas,
methods, callable class objects, partial functions, decorated functions,
anything really.A good Django citizen. Seamless integration with Django views,
templates and the Admin for testing for object-level permissions.Efficientandsmart. No need to mess around with a database to figure
out whether John really wrote that book.Simple. Dive in the code. You’ll need 10 minutes to figure out how it
works.Powerful.rulescomes complete with advanced features, such as
invocation context and storage for arbitrary data, skipping evaluation of
predicates under specific conditions, logging of evaluated predicates and more!Table of ContentsRequirementsUpgrading from 2.xUpgrading from 1.xHow to installConfiguring DjangoUsing RulesCreating predicatesSetting up rulesCombining predicatesUsing Rules with DjangoPermissionsPermissions in modelsPermissions in viewsPermissions and rules in templatesPermissions in the AdminPermissions in Django Rest FrameworkAdvanced featuresCustom rule setsInvocation contextBinding “self”Skipping predicatesLogging predicate evaluationBest practicesAPI ReferenceLicenceRequirementsrulesrequires Python 3.7 or newer. The last version to support Python 2.7
isrules2.2. It can optionally integrate with Django, in which case
requires Django 2.2 or newer.Note: At any given moment in time,ruleswill maintain support for all
currently supported Django versions, while dropping support for those versions
that reached end-of-life in minor releases. See theSupported Versionssection on Django Project website for the current state and timeline.Upgrading from 2.xThe are no significant changes betweenrules2.x and 3.x except dropping
support for Python 2, so before upgrading to 3.x you just need to make sure
you’re running a supported Python 3 version.Upgrading from 1.xSupport for Python 2.6 and 3.3, and Django versions before 1.11 has been
dropped.TheSkipPredicateexception andskip()method ofPredicate,
that were used to signify that a predicate should be skipped, have been
removed. You may returnNonefrom your predicate to achieve this.The APIs to replace a rule’s predicate have been renamed and their
behaviour changed.replace_ruleandreplace_permfunctions andreplace_rulemethod ofRuleSethave been renamed toset_rule,set_permandRuleSet.set_permrespectively. The old behaviour was
to raise aKeyErrorif a rule by the given name did not exist. Since
version 2.0 this has changed and you can safely useset_*to set a
rule’s predicate without having to ensure the rule exists first.How to installUsing pip:$pipinstallrulesManually:$gitclonehttps://github.com/dfunckt/django-rules.git$cddjango-rules$pythonsetup.pyinstallRun tests with:$./runtests.shYou may also want to readBest practicesfor general advice on how to
userules.Configuring DjangoAddrulestoINSTALLED_APPS:INSTALLED_APPS=(# ...'rules',)Add the authentication backend:AUTHENTICATION_BACKENDS=('rules.permissions.ObjectPermissionBackend','django.contrib.auth.backends.ModelBackend',)Using Rulesrulesis based on the idea that you maintain a dict-like object that maps
string keys used as identifiers of some kind, to callables, calledpredicates. This dict-like object is actually an instance ofRuleSetand
the predicates are instances ofPredicate.Creating predicatesLet’s ignore rule sets for a moment and go ahead and define a predicate. The
easiest way is with the@predicatedecorator:>>>@rules.predicate>>>defis_book_author(user,book):...returnbook.author==user...>>>is_book_author<Predicate:is_book_authorobjectat0x10eeaa490>This predicate will returnTrueif the book’s author is the given user,Falseotherwise.Predicates can be created from any callable that accepts anything from zero to
two positional arguments:fn(obj, target)fn(obj)fn()This is their generic form. If seen from the perspective of authorization in
Django, the equivalent signatures are:fn(user, obj)fn(user)fn()Predicates can do pretty much anything with the given arguments, but must
always returnTrueif the condition they check is true,Falseotherwise.rulescomes with several predefined predicates that you may
read about later on inAPI Reference, that are mostly useful when dealing
withauthorization in Django.Setting up rulesLet’s pretend that we want to let authors edit or delete their books, but not
books written by other authors. So, essentially, what determines whether an
authorcan editorcan deletea given book iswhether they are its
author.Inrules, such requirements are modelled asrules. Aruleis a map of
a unique identifier (eg. “can edit”) to a predicate. Rules are grouped
together into arule set.ruleshas two predefined rule sets:A default rule set storing shared rules.Another rule set storing rules that serve as permissions in a Django
context.So, let’s define our first couple of rules, adding them to the shared rule
set. We can use theis_book_authorpredicate we defined earlier:>>>rules.add_rule('can_edit_book',is_book_author)>>>rules.add_rule('can_delete_book',is_book_author)Assuming we’ve got some data, we can now test our rules:>>>fromdjango.contrib.auth.modelsimportUser>>>frombooks.modelsimportBook>>>guidetodjango=Book.objects.get(isbn='978-1-4302-1936-1')>>>guidetodjango.author<User:adrian>>>>adrian=User.objects.get(username='adrian')>>>rules.test_rule('can_edit_book',adrian,guidetodjango)True>>>rules.test_rule('can_delete_book',adrian,guidetodjango)TrueNice… but not awesome.Combining predicatesPredicates by themselves are not so useful – not more useful than any other
function would be. Predicates, however, can be combined using binary operators
to create more complex ones. Predicates support the following operators:P1 & P2: Returns a new predicate that returnsTrueifbothpredicates returnTrue, otherwiseFalse. If P1 returnsFalse,
P2 will not be evaluated.P1 | P2: Returns a new predicate that returnsTrueifanyof the
predicates returnsTrue, otherwiseFalse. If P1 returnsTrue,
P2 will not be evaluated.P1 ^ P2: Returns a new predicate that returnsTrueif one of the
predicates returnsTrueand the other returnsFalse, otherwiseFalse.~P: Returns a new predicate that returns the negated result of the
original predicate.Suppose the requirement for allowing a user to edit a given book was for them
to be either the book’s author, or a member of the “editors” group. Allowing
users to delete a book should still be determined by whether the user is the
book’s author.Withrulesthat’s easy to implement. We’d have to define another
predicate, that would returnTrueif the given user is a member of the
“editors” group,Falseotherwise. The built-inis_group_memberfactory
will come in handy:>>>is_editor=rules.is_group_member('editors')>>>is_editor<Predicate:is_group_member:editorsobjectat0x10eee1350>We could combine it with theis_book_authorpredicate to create a new one
that checks for either condition:>>>is_book_author_or_editor=is_book_author|is_editor>>>is_book_author_or_editor<Predicate:(is_book_author|is_group_member:editors)objectat0x10eee1390>We can now update ourcan_edit_bookrule:>>>rules.set_rule('can_edit_book',is_book_author_or_editor)>>>rules.test_rule('can_edit_book',adrian,guidetodjango)True>>>rules.test_rule('can_delete_book',adrian,guidetodjango)TrueLet’s see what happens with another user:>>>martin=User.objects.get(username='martin')>>>list(martin.groups.values_list('name',flat=True))['editors']>>>rules.test_rule('can_edit_book',martin,guidetodjango)True>>>rules.test_rule('can_delete_book',martin,guidetodjango)FalseAwesome.So far, we’ve only used the underlying, generic framework for defining and
testing rules. This layer is not at all specific to Django; it may be used in
any context. There’s actually no import of anything Django-related in the
whole app (except in therules.templatetagsmodule).ruleshowever can
integrate tightly with Django to provide authorization.Using Rules with Djangorulesis able to provide object-level permissions in Django. It comes
with an authorization backend and a couple template tags for use in your
templates.PermissionsInrules, permissions are a specialised type of rules. You still define
rules by creating and combining predicates. These rules however, must be added
to a permissions-specific rule set that comes withrulesso that they can
be picked up by therulesauthorization backend.Creating permissionsThe convention for naming permissions in Django isapp_label.action_object,
and we like to adhere to that. Let’s add rules for thebooks.change_bookandbooks.delete_bookpermissions:>>>rules.add_perm('books.change_book',is_book_author|is_editor)>>>rules.add_perm('books.delete_book',is_book_author)See the difference in the API?add_permadds to a permissions-specific
rule set, whereasadd_ruleadds to a default shared rule set. It’s
important to know however, that these two rule sets are separate, meaning that
adding a rule in one does not make it available to the other.Checking for permissionLet’s go ahead and check whetheradrianhas change permission to theguidetodjangobook:>>>adrian.has_perm('books.change_book',guidetodjango)FalseWhen you call theUser.has_permmethod, Django asks each backend insettings.AUTHENTICATION_BACKENDSwhether a user has the given permission
for the object. When queried for object permissions, Django’s default
authentication backend always returnsFalse.rulescomes with an
authorization backend, that is able to provide object-level permissions by
looking into the permissions-specific rule set.Let’s add therulesauthorization backend in settings:AUTHENTICATION_BACKENDS=('rules.permissions.ObjectPermissionBackend','django.contrib.auth.backends.ModelBackend',)Now, checking again givesadrianthe required permissions:>>>adrian.has_perm('books.change_book',guidetodjango)True>>>adrian.has_perm('books.delete_book',guidetodjango)True>>>martin.has_perm('books.change_book',guidetodjango)True>>>martin.has_perm('books.delete_book',guidetodjango)FalseNOTE:Callinghas_permon a superuser will ALWAYS returnTrue.Permissions in modelsNOTE:The features described in this section work on Python 3+ only.It is common to have a set of permissions for a model, like what Django offers with
its default model permissions (such asadd,changeetc.). When usingrulesas the permission checking backend, you can declare object-level permissions for
any model in a similar way, using a newMetaoption.First, you need to switch your model’s base and metaclass to the slightly extended
versions provided inrules.contrib.models. There are several classes and mixins
you can use, depending on whether you’re already using a custom base and/or metaclass
for your models or not. The extensions are very slim and don’t affect the models’
behavior in any way other than making it register permissions.If you’re using the stockdjango.db.models.Modelas base for your models,
simply switch over toRulesModeland you’re good to go.If you already have a custom base class adding common functionality to your models,
addRulesModelMixinto the classes it inherits from and setRulesModelBaseas its metaclass, like so:from django.db.models import Model
from rules.contrib.models import RulesModelBase, RulesModelMixin

class MyModel(RulesModelMixin, Model, metaclass=RulesModelBase):
    ...If you’re using a custom metaclass for your models, you’ll already know how to
make it inherit fromRulesModelBaseMixinyourself.Then, create your models like so, assuming you’re usingRulesModelas base
directly:import rules
from rules.contrib.models import RulesModel

class Book(RulesModel):
    class Meta:
        rules_permissions = {
            "add": rules.is_staff,
            "read": rules.is_authenticated,
        }This would be equivalent to the following calls:rules.add_perm("app_label.add_book", rules.is_staff)
rules.add_perm("app_label.read_book", rules.is_authenticated)There are methods inRulesModelMixinthat you can overwrite in order to customize
how a model’s permissions are registered. See the documented source code for details
if you need this.Of special interest is theget_permclassmethod ofRulesModelMixin, which can
be used to convert a permission type to the corresponding full permission name. If
you need to query for some type of permission on a given model programmatically,
this is handy:if user.has_perm(Book.get_perm("read")):
    ...Permissions in viewsrulescomes with a set of view decorators to help you enforce
authorization in your views.Using the function-based view decoratorFor function-based views you can use thepermission_requireddecorator:fromdjango.shortcutsimportget_object_or_404fromrules.contrib.viewsimportpermission_requiredfromposts.modelsimportPostdefget_post_by_pk(request,post_id):returnget_object_or_404(Post,pk=post_id)@permission_required('posts.change_post',fn=get_post_by_pk)defpost_update(request,post_id):# ...Usage is straight-forward, but there’s one thing in the example above that
stands out and this is theget_post_by_pkfunction. This function, given
the current request and all arguments passed to the view, is responsible for
fetching and returning the object to check permissions against – i.e. thePostinstance with PK equal to the givenpost_idin the example.
This specific use-case is quite common so, to save you some typing,rulescomes with a generic helper function that you can use to do this declaratively.
The example below is equivalent to the one above:fromrules.contrib.viewsimportpermission_required,objectgetterfromposts.modelsimportPost@permission_required('posts.change_post',fn=objectgetter(Post,'post_id'))defpost_update(request,post_id):# ...For more information on the decorator and helper function, refer to therules.contrib.viewsmodule.Using the class-based view mixinDjango includes a set of access mixins that you can use in your class-based
views to enforce authorization.rulesextends this framework to provide
object-level permissions via a mixin,PermissionRequiredMixin.The following example will automatically test for permission against the
instance returned by the view’sget_objectmethod:fromdjango.views.generic.editimportUpdateViewfromrules.contrib.viewsimportPermissionRequiredMixinfromposts.modelsimportPostclassPostUpdate(PermissionRequiredMixin,UpdateView):model=Postpermission_required='posts.change_post'You can customise the object either by overridingget_objectorget_permission_object.For more information refer to theDjango documentationand therules.contrib.viewsmodule.Checking permission automatically based on view typeIf you use the mechanisms provided byrules.contrib.modelsto register permissions
for your models as described inPermissions in models, there’s another convenient
mixin for class-based views available for you.rules.contrib.views.AutoPermissionRequiredMixincan recognize the type of view
it’s used with and check for the corresponding permission automatically.This example view would, without any further configuration, automatically check for
the"posts.change_post"permission, given that the app label is"posts":from django.views.generic import UpdateView
from rules.contrib.views import AutoPermissionRequiredMixin
from posts.models import Post

class UpdatePostView(AutoPermissionRequiredMixin, UpdateView):
    model = PostBy default, the generic CRUD views fromdjango.views.genericare mapped to the
native Django permission types (add,change,deleteandview). However,
the pre-defined mappings can be extended, changed or replaced altogether when
subclassingAutoPermissionRequiredMixin. See the fully documented source code
for details on how to do that properly.Permissions and rules in templatesrulescomes with two template tags to allow you to test for rules and
permissions in templates.Addrulesto yourINSTALLED_APPS:INSTALLED_APPS=(# ...'rules',)Then, in your template:{% load rules %}

{% has_perm 'books.change_book' author book as can_edit_book %}
{% if can_edit_book %}
    ...
{% endif %}

{% test_rule 'has_super_feature' user as has_super_feature %}
{% if has_super_feature %}
    ...
{% endif %}Permissions in the AdminIf you’ve setuprulesto be used with permissions in Django, you’re almost
set to also userulesto authorize any add/change/delete actions in the
Admin. The Admin asks forfourdifferent permissions, depending on action:<app_label>.add_<modelname><app_label>.view_<modelname><app_label>.change_<modelname><app_label>.delete_<modelname><app_label>Note:view permission is new in Django v2.1 and should not be added in versions before that.The first four are obvious. The fifth is the required permission for an app
to be displayed in the Admin’s “dashboard”. Overriding it does not restrict access to the add,
change or delete views. Here’s some rules for our imaginarybooksapp as an example:>>>rules.add_perm('books',rules.always_allow)>>>rules.add_perm('books.add_book',is_staff)>>>rules.add_perm('books.view_book',is_staff|has_secret_access_code)>>>rules.add_perm('books.change_book',is_staff)>>>rules.add_perm('books.delete_book',is_staff)Django Admin does not support object-permissions, in the sense that it will
never ask for permission to perform an actionon an object, only whether a
user is allowed to act on (any) instances of a model.If you’d like to tell Django whether a user has permissions on a specific
object, you’d have to override the following methods of a model’sModelAdmin:has_view_permission(user, obj=None)has_change_permission(user, obj=None)has_delete_permission(user, obj=None)rulescomes with a customModelAdminsubclass,rules.contrib.admin.ObjectPermissionsModelAdmin, that overrides these
methods to pass on the edited model instance to the authorization backends,
thus enabling permissions per object in the Admin:# books/admin.pyfromdjango.contribimportadminfromrules.contrib.adminimportObjectPermissionsModelAdminfrom.modelsimportBookclassBookAdmin(ObjectPermissionsModelAdmin):passadmin.site.register(Book,BookAdmin)Now this allows you to specify permissions like this:>>>rules.add_perm('books',rules.always_allow)>>>rules.add_perm('books.add_book',has_author_profile)>>>rules.add_perm('books.change_book',is_book_author_or_editor)>>>rules.add_perm('books.delete_book',is_book_author)To preserve backwards compatibility, Django will ask for eithervieworchangepermission. For maximum flexibility,rulesbehaves subtly
different:ruleswill ask for the change permission if and only if no rule
exists for the view permission.Permissions in Django Rest FrameworkSimilar torules.contrib.views.AutoPermissionRequiredMixin, there is arules.contrib.rest_framework.AutoPermissionViewSetMixinfor viewsets in Django
Rest Framework. The difference is that it doesn’t derive permission from the type
of view but from the API action (create,retrieveetc.) that’s tried to be
performed. Of course, it also requires you to declare your models as described inPermissions in models.Here is a possibleModelViewSetfor thePostmodel with fully automated CRUD
permission checking:from rest_framework.serializers import ModelSerializer
from rest_framework.viewsets import ModelViewSet
from rules.contrib.rest_framework import AutoPermissionViewSetMixin
from posts.models import Post

class PostSerializer(ModelSerializer):
    class Meta:
        model = Post
        fields = "__all__"

class PostViewSet(AutoPermissionViewSetMixin, ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializerBy default, the CRUD actions ofModelViewSetare mapped to the native
Django permission types (add,change,deleteandview). Thelistaction has no permission checking enabled. However, the pre-defined mappings
can be extended, changed or replaced altogether when using (or subclassing)AutoPermissionViewSetMixin. Custom API actions defined via the@actiondecorator may then be mapped as well. See the fully documented source code for
details on how to properly customize the default behavior.Advanced featuresCustom rule setsYou may create as many rule sets as you need:>>>features=rules.RuleSet()And manipulate them by adding, removing, querying and testing rules:>>>features.rule_exists('has_super_feature')False>>>is_special_user=rules.is_group_member('special')>>>features.add_rule('has_super_feature',is_special_user)>>>'has_super_feature'infeaturesTrue>>>features['has_super_feature']<Predicate:is_group_member:specialobjectat0x10eeaa500>>>>features.test_rule('has_super_feature',adrian)True>>>features.remove_rule('has_super_feature')Note however that custom rule sets arenot availablein Django templates –
you need to provide integration yourself.Invocation contextA new context is created as a result of invokingPredicate.test()and is
only valid for the duration of the invocation. A context is a simpledictthat you can use to store arbitrary data, (eg. caching computed values,
setting flags, etc.), that can be used by predicates later on in the chain.
Inside a predicate function it can be used like so:>>>@predicate...defmypred(a,b):...value=compute_expensive_value(a)...mypred.context['value']=value...returnTrueOther predicates can later use stored values:>>>@predicate...defmyotherpred(a,b):...value=myotherpred.context.get('value')...ifvalueisnotNone:...returndo_something_with_value(value)...else:...returndo_something_without_value()Predicate.contextprovides a singleargsattribute that contains the
arguments as given totest()at the beginning of the invocation.Binding “self”In a predicate’s function body, you can refer to the predicate instance itself
by its name, eg.is_book_author. Passingbind=Trueas a keyword
argument to thepredicatedecorator will let you refer to the predicate
withself, which is more convenient. Bindingselfis just syntactic
sugar. As a matter of fact, the following two are equivalent:>>>@predicate...defis_book_author(user,book):...ifis_book_author.context.args:...returnuser==book.author...returnFalse>>>@predicate(bind=True)...defis_book_author(self,user,book):...ifself.context.args:...returnuser==book.author...returnFalseSkipping predicatesYou may skip evaluation by returningNonefrom your predicate:>>>@predicate(bind=True)...defis_book_author(self,user,book):...iflen(self.context.args)>1:...returnuser==book.author...else:...returnNoneReturningNonesignifies that the predicate need not be evaluated, thus
leaving the predicate result up to that point unchanged.Logging predicate evaluationrulescan optionally be configured to log debug information as rules are
evaluated to help with debugging your predicates. Messages are sent at the
DEBUG level to the'rules'logger. The followingdictConfigconfigures
a console logger (place this in your project’ssettings.pyif you’re usingruleswith Django):LOGGING={'version':1,'disable_existing_loggers':False,'handlers':{'console':{'level':'DEBUG','class':'logging.StreamHandler',},},'loggers':{'rules':{'handlers':['console'],'level':'DEBUG','propagate':True,},},}When this logger is active each individual predicate will have a log message
printed when it is evaluated.Best practicesBefore you can test for rules, these rules must be registered with a rule set,
and for this to happen the modules containing your rule definitions must be
imported.For complex projects with several predicates and rules, it may not be
practical to define all your predicates and rules inside one module. It might
be best to split them among any sub-components of your project. In a Django
context, these sub-components could be the apps for your project.On the other hand, because importing predicates from all over the place in
order to define rules can lead to circular imports and broken hearts, it’s
best to further split predicates and rules in different modules.rulesmay optionally be configured to autodiscoverrules.pymodules in
your apps and import them at startup. To haverulesdo so, just edit yourINSTALLED_APPSsetting:INSTALLED_APPS=(# replace 'rules' with:'rules.apps.AutodiscoverRulesConfig',)Note:On Python 2, you must also add the following to the top of yourrules.pyfile, or you’ll get import errors trying to importrulesitself:from__future__importabsolute_importAPI ReferenceThe core APIs are accessible from the rootrulesmodule. Django-specific
functionality for the Admin and views is available fromrules.contrib.Classrules.PredicateYou createPredicateinstances by passing in a callable:>>>defis_book_author(user,book):...returnbook.author==user...>>>pred=Predicate(is_book_author)>>>pred<Predicate:is_book_authorobjectat0x10eeaa490>You may optionally provide a different name for the predicate that is used
when inspecting it:>>>pred=Predicate(is_book_author,name='another_name')>>>pred<Predicate:another_nameobjectat0x10eeaa490>Also, you may optionally providebind=Truein order to be able to access
the predicate instance withself:>>>defis_book_author(self,user,book):...ifself.context.args:...returnuser==book.author...returnFalse...>>>pred=Predicate(is_book_author,bind=True)>>>pred<Predicate:is_book_authorobjectat0x10eeaa490>Instance methodstest(obj=None, target=None)Returns the result of calling the passed in callable with zero, one or two
positional arguments, depending on how many it accepts.Classrules.RuleSetRuleSetextends Python’s built-indicttype. Therefore, you may create
and use a rule set any way you’d use a dict.Instance methodsadd_rule(name, predicate)Adds a predicate to the rule set, assigning it to the given rule name.
RaisesKeyErrorif another rule with that name already exists.set_rule(name, predicate)Set the rule with the given name, regardless if one already exists.remove_rule(name)Remove the rule with the given name. RaisesKeyErrorif a rule with
that name does not exist.rule_exists(name)ReturnsTrueif a rule with the given name exists,Falseotherwise.test_rule(name, obj=None, target=None)Returns the result of callingpredicate.test(obj, target)wherepredicateis the predicate for the rule with the given name. ReturnsFalseif a rule with the given name does not exist.Decorators@predicateDecorator that creates a predicate out of any callable:>>>@predicate...defis_book_author(user,book):...returnbook.author==user...>>>is_book_author<Predicate:is_book_authorobjectat0x10eeaa490>Customising the predicate name:>>>@predicate(name='another_name')...defis_book_author(user,book):...returnbook.author==user...>>>is_book_author<Predicate:another_nameobjectat0x10eeaa490>Bindingself:>>>@predicate(bind=True)...defis_book_author(self,user,book):...if'user_has_special_flag'inself.context:...returnself.context['user_has_special_flag']...returnbook.author==userPredefined predicatesalways_allow(),always_true()Always returnsTrue.always_deny(),always_false()Always returnsFalse.is_authenticated(user)Returns the result of callinguser.is_authenticated(). ReturnsFalseif the given user does not have anis_authenticatedmethod.is_superuser(user)Returns the result of callinguser.is_superuser. ReturnsFalseif the given user does not have anis_superuserproperty.is_staff(user)Returns the result of callinguser.is_staff. ReturnsFalseif the
given user does not have anis_staffproperty.is_active(user)Returns the result of callinguser.is_active. ReturnsFalseif the
given user does not have anis_activeproperty.is_group_member(*groups)Factory that creates a new predicate that returnsTrueif the given
user is a member ofallthe given groups,Falseotherwise.ShortcutsManaging the shared rule setadd_rule(name, predicate)Adds a rule to the shared rule set. SeeRuleSet.add_rule.set_rule(name, predicate)Set the rule with the given name from the shared rule set. SeeRuleSet.set_rule.remove_rule(name)Remove a rule from the shared rule set. SeeRuleSet.remove_rule.rule_exists(name)Returns whether a rule exists in the shared rule set. SeeRuleSet.rule_exists.test_rule(name, obj=None, target=None)Tests the rule with the given name. SeeRuleSet.test_rule.Managing the permissions rule setadd_perm(name, predicate)Adds a rule to the permissions rule set. SeeRuleSet.add_rule.set_perm(name, predicate)Replace a rule from the permissions rule set. SeeRuleSet.set_rule.remove_perm(name)Remove a rule from the permissions rule set. SeeRuleSet.remove_rule.perm_exists(name)Returns whether a rule exists in the permissions rule set. SeeRuleSet.rule_exists.has_perm(name, user=None, obj=None)Tests the rule with the given name. SeeRuleSet.test_rule.Licencedjango-rulesis distributed under the MIT licence.Copyright (c) 2014 Akis KesoglouPermission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the “Software”), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.