Python
Creating a Spice Function in Python
In the
function.yaml
, code execution runtime and invocation handler is defined.# hello_world/function.yaml
output_dataset: hello_world
# This will trigger the function to execute on every new Ethereum block.
triggers:
- path: eth
# This selects the runtime that will execute your code.
runtime: python3.11
# For Python, handler is [script_name].[method]
# The below will invoke a method `process` in a file `spice_function.py`.
handler: spice_function.process
A Python invocation handler method has the following signature:
def process(context: dict,
duckdb: duckdb.DuckDBPyConnection,
spice_client: spicepy.Client):
context
: A dictionary with context variables, E.g.block_number
andblock_hash
duckdb
: A connection to the Spice Function's DuckDB instance.
The handler method will be called on each triggered event.
Python dependencies can be specified by placing a
requirements.txt
adjacent to the code importing the dependencies.The Python function runtime comes pre-loaded with these modules:
Currently, Python modules that depend on compiled C extensions are not supported to be defined in requirements.txt. A request for a particular missing dependency may be made on Discord.
An example Python function that will produce the same outputs shown above:
# hello_world/spice_function.py
import duckdb
import spicepy
def process(context: dict,
duckdb: duckdb.DuckDBPyConnection,
spice_client: spicepy.Client):
# Temporary step
duckdb.sql("""CREATE TABLE IF NOT EXISTS output.hello_world (
block_number BIGINT,
greeting TEXT
)""")
duckdb.sql(f"INSERT INTO output.hello_world VALUES ({context['block_number']}, 'Hello!')")
print("Hello, World!")
Last modified 1mo ago