Skip to content

Repository files navigation

Mutations

pypi-version

Compose your business logic into commands that sanitize and validate input.

Install

$ pip install mutations

How it Works:

  1. Subclass mutations.Mutation
  2. Define your inputs.
  3. Define an execute method in your command.
  4. Run it, like this: SimpleMutation.run(foo='bar')

To learn more, see this blog post.

Example

importmutationsclassUserSignup(mutations.Mutation):
"""Define the inputs to your mutation here. """email=mutations.fields.CharField(required=True)
full_name=mutations.fields.CharField(required=True)
send_welcome_email=mutations.fields.Boolean(required=False, default=True)
defvalidate_email_address(self):
"""Custom validation for a field. If you encounter any validation errors and want to raise, you should raise mutation.ValidationError or some sublcass thereof. Otherwise, it assumes there were no problems. Any function beginning with `validate_` is assumed to be a validator function and will be run before the mutation can execute. """ifnotself.email.is_valid():
raisemutations.ValidationError("email_not_valid", "Email is not valid.")
defexecute(self):
"""Executes the mutation. This method does the heavy lifting. You can call it by calling .run() on your mutation class. """user=User.objects.create(email=self.email, name=self.full_name)
ifself.send_welcome_email:
EmailServer.deliver(recipient=self.email)
returnuser

Calling Commands

>>>result=UserSignup.run(email=email, full_name="Bob Boblob")
>>>result.successTrue>>>result.return_value<Userid=...>>>>result.errorsresult= ...
>>>result=UserSignup.run(email=None)
>>>result.successFalse>>>result.errorsmutations.ErrorDict({
'email': ['email_not_valid']
})
>>>result.valueNone

Only Run Validations

>>>result=UserSignup.validate(email=email, full_name="Bob Boblob")
>>>result.is_validTrue

Testing

$ make tests

When you're ready to do a release, please make sure tests pass across both 2.7 and 3.6 by running tox:

$ tox

Versioning

This project uses Semantic Versioning.

Thanks

Thanks to Cypriss for the excellent Ruby Mutations Gem. I created this library because I was looking for something similar for Python.

About

Compose your business logic into commands that sanitize and validate input.

Resources

Stars

55 stars

Watchers

3 watching

Forks

Releases

Packages

Used by

Contributors

Languages