Skip to content

Instantly share code, notes, and snippets.

@rbrady
Last active March 9, 2017 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rbrady/248cb52d5c5f94854d8c76eee911ce8e to your computer and use it in GitHub Desktop.
Save rbrady/248cb52d5c5f94854d8c76eee911ce8e to your computer and use it in GitHub Desktop.
Mistral Custom Actions ~ With Mixins (Usage)
import base
class MyCustomAction(base.Action):
def run(self):
return "I ran"
class MyAsyncAction(base.AsyncMixin, base.Action):
def run(self):
return "I have the is_sync method: %s" % hasattr(self, "is_sync")
class MyContextAction(base.ContextMixin, base.Action):
def run(self):
return "I have a context: %s" % self.context
# extensibiltiy scenario: an asynchronous action that requires a context
# note using this scenario differs from the base class scenario as it does not
# require you to redefine is_sync. Net result is cleaner extensibility with
# mixins.
class AsyncContextAction(base.ContextMixin, base.AsyncMixin, base.Action):
def run(self):
return "I have the is_sync method: %s and I have a context: %s" % (
hasattr(self, "is_sync"),
self.context
)
# basic custom action
a = MyCustomAction()
a.run()
# asynchronous action
b = MyAsyncAction()
# current test in mistral for is_sync tests for is_sync.
# The new example remains backwards compatible.
is_sync = b.is_sync()
# alternate tests for the AsyncMixin
# 1) class inheritance. (Is-A)
# The following wouldn't require the presence of the is_sync method and could
# be tested against all actions, regardless of base type
is_sync = not isinstance(b, "AsyncMixin")
# 2) function existence
# this line tests for presence of the method and is likely considered more "pythonic"
# this would also make more sense if the method on the AsyncMixin was named "is_async"
is_sync = callable(getattr(b, 'is_sync', None))
# run to stay complete with the other examples
b.run()
context = {"name": "someval"}
c = MyContextAction()
# Current actions in Mistral would be unharmed and backwards compatible
# we would simply add the following block to ensure new actions would
# get the context as needed
if isinstance(c, "ContextMixin"):
c.set_context(context)
c.run()
@Toure
Copy link

Toure commented Mar 9, 2017

Class name should not be wrapped in quotes.

@Toure
Copy link

Toure commented Mar 9, 2017

Are you relying on the user to provide the context or would oslo.context be used?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment