ViaPyodide ↗, Python Workers provide aForeign Function Interface (FFI) ↗ to JavaScript. This allows you to:
- Usebindings to resources on Cloudflare, includingWorkers AI,Vectorize,R2,KV,D1,Queues,Durable Objects,Service Bindings and more.
- Use JavaScript globals, like
Request,Response, andfetch(). - Use the full feature set of Cloudflare Workers — if an API is accessible in JavaScript, you can also access it in a Python Worker, writing exclusively Python code.
The details of Pyodide's Foreign Function Interface are documentedhere ↗, and Workers written in Python are able to take full advantage of this.
Bindings allow your Worker to interact with resources on the Cloudflare Developer Platform. When you declare a binding on your Worker, you grant it a specific capability, such as being able to read and write files to anR2 bucket.
For example, to access aKV namespace from a Python Worker, you would declare the following in your Worker'sWrangler configuration file:
{"main":"./src/index.py","kv_namespaces":[{"binding":"FOO","id":"<YOUR_KV_NAMESPACE_ID>"}]}main="./src/index.py"[[kv_namespaces]]binding="FOO"id="<YOUR_KV_NAMESPACE_ID>"...and then call.get() on the binding object that is exposed onenv:
from workersimport WorkerEntrypoint, ResponseclassDefault(WorkerEntrypoint):asyncdeffetch(self,request):awaitself.env.FOO.put("bar","baz")bar=awaitself.env.FOO.get("bar")returnResponse(bar)# returns "baz"Under the hood,env is actually a JavaScript object. When you call.FOO, you are accessing this property via aJsProxy ↗ — special proxy object that makes a JavaScript object behave like a Python object.
Occasionally, to interoperate with JavaScript APIs, you may need to convert a Python object to JavaScript. Pyodide provides ato_js function to facilitate this conversion.
from jsimport Objectfrom pyodide.ffiimport to_jsas _to_jsfrom workersimport WorkerEntrypoint, Response# to_js converts between Python dictionaries and JavaScript Objectsdefto_js(obj):return_to_js(obj,dict_converter=Object.fromEntries)```For more details, see out thedocumentation onpyodide.ffi.to_js ↗.
When writing Workers in Python, you can access JavaScript globals by importing them from thejs module. For example, note howResponse is imported fromjs in the example below:
from workersimport WorkerEntrypointfrom jsimport ResponseclassDefault(WorkerEntrypoint):asyncdeffetch(self,request):return Response.new("Hello World!")Refer to thePython examples to learn how to call into JavaScript functions from Python, includingconsole.log and logging, providing options toResponse, and parsing JSON.