Help Center/ FunctionGraph/ devg/ Python/ Python Template
Updated on 2023-06-19 GMT+08:00

Python Template

Stateful function:

# funcName: pythonstateful
# Stateful functions must implement an initialization API.
from functionsdk import Function
def initState(event, context):
    state = {"counter": 0}
    context.set_state(state)

def myHandler(event, context):
    # process req
    state = context.get_state()
    # process state
    state["counter"] += 1
    context.set_state(state)
    # function object
    func = Function(context)
    # persistent state
    func.save_state()
return state

Invoking function:

# funcName: pythoncaller

from functionsdk import Function
def newStateRouter(event, context):
    func = Function(context, "pythonstateful", "test1")
    instanceID = func.get_instance_id()
    return instanceID

def bindStateRouter(event, context):
    func = Function(context)
    # bind
    func.get_instance("pythonstateful", "test1")
    instanceID = func.get_instance_id()
    return instanceID

def invoke(event, context):
    func = Function(context)
    # bind
    func.get_instance("pythonstateful", "test1")
    obj = func.invoke("{\"key\":\"value\"}")
    result = obj.get()
    return result

def terminate(event, context):
    func = Function(context)
    # bind
    func.get_instance("pythonstateful", "test1")
    obj = func.terminate()
    result = obj.get()
return result