Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Cloudflare Docs
Log in

ViaPyodide, Python Workers provide aForeign Function Interface (FFI) to JavaScript. This allows you to:

The details of Pyodide's Foreign Function Interface are documentedhere, and Workers written in Python are able to take full advantage of this.

Using Bindings from Python Workers

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>"
}
]
}

...and then call.get() on the binding object that is exposed onenv:

Python
from workersimport WorkerEntrypoint, Response
classDefault(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.

Converting Python to JavaScript

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.

Python
from jsimport Object
from pyodide.ffiimport to_jsas _to_js
from workersimport WorkerEntrypoint, Response
# to_js converts between Python dictionaries and JavaScript Objects
defto_js(obj):
return_to_js(obj,dict_converter=Object.fromEntries)
```

For more details, see out thedocumentation onpyodide.ffi.to_js.

Using JavaScript globals from Python Workers

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:

Python
from workersimport WorkerEntrypoint
from jsimport Response
classDefault(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.


[8]
ページ先頭

©2009-2026 Movatter.jp