from statefun import StatefulFunctionsfunctions =StatefulFunctions()@functions.bind("example/hello")defhello_function(context,message):"""A simple hello world function""" user =User() message.Unpack(user)print("Hello "+ user.name)
import typingfrom statefun import StatefulFunctionsfunctions =StatefulFunctions()@functions.bind("example/hello")defhello_function(context,message: User):"""A simple hello world function with typing"""print("Hello "+ message.name)@function.bind("example/goodbye")defgoodbye_function(context,message: typing.Union[User, Admin]):"""A function that dispatches on types"""ifisinstance(message, User):print("Goodbye user")elifisinstance(message, Admin):print("Goodbye Admin")
from google.protobuf.any_pb2 import Anyfrom statefun import StatefulFunctionsfunctions =StatefulFunctions()@functions.bind("example/caller")defcaller_function(context,message):"""A simple stateful function that sends a message to the user with id `user1`""" user =User() user.user_id ="user1" user.name ="Seth" envelope =Any() envelope.Pack(user) context.send("example/hello", user.user_id, envelope)
from google.protobuf.any_pb2 import Anyfrom statefun import StatefulFunctionsfunctions =StatefulFunctions()@functions.bind("example/caller")defcaller_function(context,message):"""A simple stateful function that sends a message to the user with id `user1`""" user =User() user.user_id ="user1" user.name ="Seth" envelope =Any() envelope.Pack(user) context.send("example/hello", user.user_id, envelope)
from google.protobuf.any_pb2 import Anyfrom statefun import StatefulFunctionsfunctions =StatefulFunctions()@functions.bind("example/count")defcount_greeter(context,message):"""Function that greets a user based on the number of times it has been called""" user =User() message.Unpack(user) state = context["count"]if state isNone: state =Any() state.Pack(Count(1)) output =generate_message(1, user)else: counter =Count() state.Unpack(counter) counter.value +=1 output =generate_message(counter.value, user) state.Pack(counter) context["count"]= stateprint(output)defgenerate_message(count,user):if count ==1:return"Hello "+ user.nameelif count ==2:return"Hello again!"elif count ==3:return"Third time's the charm"else:return"Hello for the "+ count +"th time"