Files
extism/python/example.py
zach 87be73570d Add ExtismContext to SDK + better errors for failed register/update (#19)
- Adds `ExtismContext` instead of global `PLUGINS` registry
- Adds `extism_context_new`, `extism_context_free` and
`extism_context_reset`
- Requires updating nearly every SDK function to add context parameter
- Renames some SDK functions to follow better naming conventions
   - `extism_plugin_register` -> `extism_plugin_new`
   - `extism_output_get` -> `extism_plugin_output_data`
   - `extism_output_length` -> `extism_plugin_output_length`
   - `extism_call` -> `extism_plugin_call`
- Updates `extism_error` to return the context error when -1 issued for
the plug-in ID
- Adds `extism_plugin_free` to remove an existing plugin
- Updates SDKs to include these functions
- Updates SDK examples and comments

Co-authored-by: Steve Manuel <steve@dylib.so>
2022-09-20 14:53:15 -06:00

37 lines
935 B
Python

import sys
import os
import json
import hashlib
sys.path.append(".")
from extism import Plugin, Context
if len(sys.argv) > 1:
data = sys.argv[1].encode()
else:
data = b"some data from python!"
# a Context provides a scope for plugins to be managed within. creating multiple contexts
# is expected and groups plugins based on source/tenant/lifetime etc.
with Context() as context:
wasm = open("../wasm/code.wasm", 'rb').read()
hash = hashlib.sha256(wasm).hexdigest()
config = {"wasm": [{"data": wasm, "hash": hash}], "memory": {"max": 5}}
plugin = context.plugin(config)
# Call `count_vowels`
j = json.loads(plugin.call("count_vowels", data))
print("Number of vowels:", j["count"])
# Compare against Python implementation
def count_vowels(data):
count = 0
for c in data:
if c in b'AaEeIiOoUu':
count += 1
return count
assert (j["count"] == count_vowels(data))