Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 16 additions & 14 deletions src/content/docs/workers/languages/python/examples.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,19 @@ 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)
# Parse the query parameters into a Python dictionary
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)


Expand All @@ -37,22 +39,24 @@ 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

```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
Expand All @@ -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/
Expand All @@ -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"})
Expand All @@ -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
Expand Down
23 changes: 16 additions & 7 deletions src/content/docs/workers/languages/python/index.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"))
```
Expand All @@ -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))
```

Expand Down Expand Up @@ -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)
```
Expand Down
Loading