diff --git a/src/content/docs/workers/languages/python/examples.mdx b/src/content/docs/workers/languages/python/examples.mdx index a083955863c2683..032941c19f52e9d 100644 --- a/src/content/docs/workers/languages/python/examples.mdx +++ b/src/content/docs/workers/languages/python/examples.mdx @@ -14,9 +14,10 @@ In addition to those examples, consider the following ones that illustrate Pytho ## Parse an incoming request URL ```python -from workers import Response +from workers import handler, Response from urllib.parse import urlparse, parse_qs +@handler async def on_fetch(request, env): # Parse the incoming request URL url = urlparse(request.url) @@ -24,7 +25,8 @@ async def on_fetch(request, env): params = parse_qs(url.query) if "name" in params: - greeting = "Hello there, {name}".format(name=params["name"][0]) + name = params["name"][0] + greeting = f"Hello there, {name}" return Response(greeting) @@ -37,11 +39,12 @@ async def on_fetch(request, env): ## Parse JSON from the incoming request ```python -from workers import Response +from workers import handler, Response +@handler async def on_fetch(request): - name = (await request.json()).name - return Response("Hello, {name}".format(name=name)) + name = (await request.json())["name"] + return Response(f"Hello, {name}") ``` ## Emit logs from your Python Worker @@ -49,10 +52,11 @@ async def on_fetch(request): ```python # To use the JavaScript console APIs from js import console -from workers import Response +from workers import handler, Response # To use the native Python logging import logging +@handler async def on_fetch(request): # Use the console APIs from JavaScript # https://developer.mozilla.org/en-US/docs/Web/API/console @@ -77,14 +81,11 @@ async def on_fetch(request): ```python from js import Object -from pyodide.ffi import to_js as _to_js +import json -from workers import Response - -# to_js converts between Python dictionaries and JavaScript Objects -def to_js(obj): - return _to_js(obj, dict_converter=Object.fromEntries) +from workers import handler, Response +@handler async def on_fetch(request, env): # Bindings are available on the 'env' parameter # https://developers.cloudflare.com/queues/ @@ -93,7 +94,7 @@ async def on_fetch(request, env): # We can also pass plain text strings await env.QUEUE.send("hello", contentType="text") # Send a JSON payload - await env.QUEUE.send(to_js({"hello": "world"})) + await env.QUEUE.send(json.dumps({"hello": "world"})) # Return a response return Response.json({"write": "success"}) @@ -102,8 +103,9 @@ async def on_fetch(request, env): ## Query a D1 Database ```python -from workers import Response +from workers import handler, Response +@handler async def on_fetch(request, env): results = await env.DB.prepare("PRAGMA table_list").all() # Return a JSON response diff --git a/src/content/docs/workers/languages/python/index.mdx b/src/content/docs/workers/languages/python/index.mdx index d26ffa44db61258..b8192ac46b8d6ec 100644 --- a/src/content/docs/workers/languages/python/index.mdx +++ b/src/content/docs/workers/languages/python/index.mdx @@ -38,17 +38,23 @@ cd python-workers-examples/01-hello npx wrangler@latest dev ``` -A Python Worker can be as simple as three lines of code: +A Python Worker can be as simple as four lines of code: ```python -from workers import Response +from workers import handler, Response +@handler def on_fetch(request): return Response("Hello World!") ``` Similar to Workers written in [JavaScript](/workers/languages/javascript), [TypeScript](/workers/languages/typescript), or [Rust](/workers/languages/rust/), the main entry point for a Python worker is the [`fetch` handler](/workers/runtime-apis/handlers/fetch). In a Python Worker, this handler is named `on_fetch`. +Additionally there is a `@handler` wrapper function used to nativize the on_fetch handler; the inline documentation states: +> When applied to handlers such as `on_fetch` it will rewrite arguments passed in to native Python +> types defined in this module. For example, the `request` argument to `on_fetch` gets converted +> to an instance of the Request class defined in this module. + To run a Python Worker locally, you use [Wrangler](/workers/wrangler/), the CLI for Cloudflare Workers: ```bash @@ -67,15 +73,16 @@ Python workers can be split across multiple files. Let's create a new Python fil ```python def hello(name): - return "Hello, " + name + "!" + return f"Hello, {name}!" ``` Now, we can modify `src/entry.py` to make use of the new module. ```python from hello import hello -from workers import Response +from workers import handler, Response +@handler def on_fetch(request): return Response(hello("World")) ``` @@ -93,11 +100,12 @@ Let's try editing the worker to accept a POST request. We know from the JSON. In a Python Worker, you would write: ```python -from workers import Response +from workers import handler, Response from hello import hello +@handler async def on_fetch(request): - name = (await request.json()).name + name = (await request.json())["name"] return Response(hello(name)) ``` @@ -142,8 +150,9 @@ API_HOST = "example.com" Then, you can access the `API_HOST` environment variable via the `env` parameter: ```python -from workers import Response +from workers import handler, Response +@handler async def on_fetch(request, env): return Response(env.API_HOST) ```