Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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