### Navigation

- index
- modules |
- next |
- previous |
- repoze.what 1.0.9 documentation »
- The `repoze.what` Manual »
- Controlling access with predicates »

# Built-in predicate checkers

These are the predicate checkers that are included with `repoze.what`:

## The base `Predicate` class

`Predicate` is the parent class of every predicate checker and its API is described below:

class `repoze.what.predicates.``Predicate`(msg=None)

  Generic predicate checker.

  This is the base predicate class. It won’t do anything useful for you, unless you subclass it.

  `__init__`(msg=None)

    Create a predicate and use `msg` as the error message if it fails.

    Parameters: | msg (str) – The error message, if you want to override the default one defined by the predicate.

    You may use the `msg` keyword argument with any predicate.

  `evaluate`(environ, credentials)

    Raise an exception if the predicate is not met.

    Parameters:

    - environ (dict) – The WSGI environment.
    - credentials (dict) – The `repoze.what` `credentials` dictionary as a short-cut.

    Raises:

    - NotImplementedError – When the predicate doesn’t define this method.
    - NotAuthorizedError – If the predicate is not met (use `unmet()` to raise it).

    This is the method that must be overridden by any predicate checker.

    For example, if your predicate is “The current month is the specified one”, you may define the following predicate checker:

        from datetime import date
        from repoze.what.predicates import Predicate

        class is_month(Predicate):
            message = 'The current month must be %(right_month)s'

            def __init__(self, right_month, **kwargs):
                self.right_month = right_month
                super(is_month, self).__init__(**kwargs)

            def evaluate(self, environ, credentials):
                today = date.today()
                if today.month != self.right_month:
                    # Raise an exception because the predicate is not met.
                    self.unmet()

    New in version 1.0.2.

    Warning

    To make your predicates thread-safe, keep in mind that they may be instantiated at module-level and then shared among many threads, so avoid predicates from being modified after their evaluation. This is, the `evaluate()` method should not add, modify or delete any attribute of the predicate.

  `unmet`(msg=None, **placeholders)

    Raise an exception because this predicate is not met.

    Parameters: | msg (str) – The error message to be used; overrides the predicate’s default one.
    Raises NotAuthorizedError:
    | If the predicate is not met.

    `placeholders` represent the placeholders for the predicate message. The predicate’s attributes will also be taken into account while creating the message with its placeholders.

    For example, if you have a predicate that checks that the current month is the specified one, where the predicate message is defined with two placeholders as in:

        The current month must be %(right_month)s and it is %(this_month)s

    and the predicate has an attribute called `right_month` which represents the expected month, then you can use this method as in:

        self.unmet(this_month=this_month)

    Then `unmet()` will build the message using the `this_month` keyword argument and the `right_month` attribute as the placeholders for `this_month` and `right_month`, respectively. So, if `this_month` equals `3` and `right_month` equals `5`, the message for the exception to be raised will be:

        The current month must be 5 and it is 3

    If you have a context-sensitive predicate checker and thus you want to change the error message on evaluation, you can call `unmet()` as:

        self.unmet('%(this_month)s is not a good month',
                   this_month=this_month)

    The exception raised would contain the following message:

        3 is not a good month

    New in version 1.0.2.

    Changed in version 1.0.4: Introduced the `msg` argument.

    Attention

    This method should only be called from `evaluate()`.

  `check_authorization`(environ)

    Evaluate the predicate and raise an exception if it’s not met.

    Parameters: | environ – The WSGI environment.
    Raises NotAuthorizedError:
    | If it the predicate is not met.

    Example:

        >>> from repoze.what.predicates import is_user
        >>> environ = gimme_the_environ()
        >>> p = is_user('gustavo')
        >>> p.check_authorization(environ)
        # ...
        repoze.what.predicates.NotAuthorizedError: The current user must be "gustavo"

    New in version 1.0.4: Backported from `repoze.what` v2; deprecates `repoze.what.authorize.check_authorization()`.

  `is_met`(environ)

    Find whether the predicate is met or not.

    Parameters: | environ – The WSGI environment.
    Returns: | Whether the predicate is met or not.
    Return type: | bool

    Example:

        >>> from repoze.what.predicates import is_user
        >>> environ = gimme_the_environ()
        >>> p = is_user('gustavo')
        >>> p.is_met(environ)
        False

    New in version 1.0.4: Backported from `repoze.what` v2.

  `parse_variables`(environ)

    Return the GET and POST variables in the request, as well as `wsgiorg.routing_args` arguments.

    Parameters: | environ – The WSGI environ.
    Returns: | The GET and POST variables and `wsgiorg.routing_args` arguments.
    Return type: | dict

    This is a handy method for request-sensitive predicate checkers.

    It will return a dictionary for the POST and GET variables, as well as the wsgiorg.routing_args‘s `positional_args` and `named_args` arguments, in the `post`, `get`, `positional_args` and `named_args` items (respectively) of the returned dictionary.

    For example, if the user submits a form using the POST method to `http://example.com/blog/hello-world/edit_post?wysiwyg_editor=Yes`, this method may return:

        {
        'post': {'new_post_contents': 'These are the new contents'},
        'get': {'wysiwyg_editor': 'Yes'},
        'named_args': {'post_slug': 'hello-world'},
        'positional_args': (),
        }

    But note that the `named_args` and `positional_args` items depend completely on how you configured the dispatcher.

    New in version 1.0.4.

  `_eval_with_environ`(environ)

    Check whether the predicate is met.

    Parameters: | environ (dict) – The WSGI environment.
    Returns: | Whether the predicate is met or not.
    Return type: | bool
    Raises NotImplementedError:
    | This must be defined by the predicate itself.

    Deprecated since version 1.0.2: Only `evaluate()` will be used as of `repoze.what` v2.

## Single predicate checkers

class `repoze.what.predicates.``is_user`(user_name, **kwargs)

  Check that the authenticated user’s username is the specified one.

  Parameters: | user_name (str) – The required user name.

  Example:

      p = is_user('linus')

class `repoze.what.predicates.``not_anonymous`(msg=None)

  Check that the current user has been authenticated.

  Example:

      # The user must have been authenticated!
      p = not_anonymous()

class `repoze.what.predicates.``is_anonymous`(msg=None)

  Check that the current user is anonymous.

  Example:

      # The user must be anonymous!
      p = is_anonymous()

  New in version 1.0.7.

class `repoze.what.predicates.``in_group`(group_name, **kwargs)

  Check that the user belongs to the specified group.

  Parameters: | group_name (str) – The name of the group to which the user must belong.

  Example:

      p = in_group('customers')

class `repoze.what.predicates.``in_all_groups`(*groups, **kwargs)

  Check that the user belongs to all of the specified groups.

  Parameters: | groups – The name of all the groups the user must belong to.

  Example:

      p = in_all_groups('developers', 'designers')

class `repoze.what.predicates.``in_any_group`(*groups, **kwargs)

  Check that the user belongs to at least one of the specified groups.

  Parameters: | groups – The name of any of the groups the user may belong to.

  Example:

      p = in_any_group('directors', 'hr')

class `repoze.what.predicates.``has_permission`(permission_name, **kwargs)

  Check that the current user has the specified permission.

  Parameters: | permission_name – The name of the permission that must be granted to the user.

  Example:

      p = has_permission('hire')

class `repoze.what.predicates.``has_all_permissions`(*permissions, **kwargs)

  Check that the current user has been granted all of the specified permissions.

  Parameters: | permissions – The names of all the permissions that must be granted to the user.

  Example:

      p = has_all_permissions('view-users', 'edit-users')

class `repoze.what.predicates.``has_any_permission`(*permissions, **kwargs)

  Check that the user has at least one of the specified permissions.

  Parameters: | permissions – The names of any of the permissions that have to be granted to the user.

  Example:

      p = has_any_permission('manage-users', 'edit-users')

class `repoze.what.predicates.``Not`(predicate, **kwargs)

  Negate the specified predicate.

  Parameters: | predicate – The predicate to be negated.

  Example:

      # The user *must* be anonymous:
      p = Not(not_anonymous())

## Compound predicate checkers

You may create a compound predicate by aggregating single (or even compound) predicate checkers with the functions below:

class `repoze.what.predicates.``All`(*predicates, **kwargs)

  Check that all of the specified predicates are met.

  Parameters: | predicates – All of the predicates that must be met.

  Example:

      # Grant access if the current month is July and the user belongs to
      # the human resources group.
      p = All(is_month(7), in_group('hr'))

class `repoze.what.predicates.``Any`(*predicates, **kwargs)

  Check that at least one of the specified predicates is met.

  Parameters: | predicates – Any of the predicates that must be met.

  Example:

      # Grant access if the currest user is Richard Stallman or Linus
      # Torvalds.
      p = Any(is_user('rms'), is_user('linus'))

But you can also nest compound predicates:

    p = All(Any(is_month(4), is_month(10)), has_permission('release'))

Which may be translated as “Anyone granted the ‘release’ permission may release a version of Ubuntu, if and only if it’s April or October”.

## Predicate errors

class `repoze.what.predicates.``NotAuthorizedError`

  Exception raised by `Predicate.check_authorization()` if the subject is not allowed to access the requested source.

  This exception deprecates `PredicateError` as of v1.0.4, but extends it to avoid breaking backwards compatibility.

  Changed in version 1.0.4: This exception was defined at `repoze.what.authorize` until version 1.0.3, but is still imported into that module to keep backwards compatibility with v1.X releases – but it won’t work in `repoze.what` v2.

class `repoze.what.predicates.``PredicateError`

  Former exception raised by a `Predicate` if it’s not met.

  Deprecated since version 1.0.4: Deprecated in favor of `NotAuthorizedError`, for forward compatibility with `repoze.what` v2.

### Navigation

- index
- modules |
- next |
- previous |
- repoze.what 1.0.9 documentation »
- The `repoze.what` Manual »
- Controlling access with predicates »