Skip to content

Commit 5fe9fba

Browse files
committed
Updated index to also use @handler and add a bit of background
1 parent 3147599 commit 5fe9fba

File tree

1 file changed

+14
-5
lines changed
  • src/content/docs/workers/languages/python

1 file changed

+14
-5
lines changed

src/content/docs/workers/languages/python/index.mdx

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -38,17 +38,23 @@ cd python-workers-examples/01-hello
3838
npx wrangler@latest dev
3939
```
4040

41-
A Python Worker can be as simple as three lines of code:
41+
A Python Worker can be as simple as four lines of code:
4242

4343
```python
44-
from workers import Response
44+
from workers import handler, Response
4545

46+
@handler
4647
def on_fetch(request):
4748
return Response("Hello World!")
4849
```
4950

5051
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`.
5152

53+
Additionally there is a `@handler` wrapper function used to nativize the on_fetch handler; the inline documentation states:
54+
> When applied to handlers such as `on_fetch` it will rewrite arguments passed in to native Python
55+
> types defined in this module. For example, the `request` argument to `on_fetch` gets converted
56+
> to an instance of the Request class defined in this module.
57+
5258
To run a Python Worker locally, you use [Wrangler](/workers/wrangler/), the CLI for Cloudflare Workers:
5359

5460
```bash
@@ -74,8 +80,9 @@ Now, we can modify `src/entry.py` to make use of the new module.
7480

7581
```python
7682
from hello import hello
77-
from workers import Response
83+
from workers import handler, Response
7884

85+
@handler
7986
def on_fetch(request):
8087
return Response(hello("World"))
8188
```
@@ -93,9 +100,10 @@ Let's try editing the worker to accept a POST request. We know from the
93100
JSON. In a Python Worker, you would write:
94101

95102
```python
96-
from workers import Response
103+
from workers import handler, Response
97104
from hello import hello
98105

106+
@handler
99107
async def on_fetch(request):
100108
name = (await request.json())["name"]
101109
return Response(hello(name))
@@ -142,8 +150,9 @@ API_HOST = "example.com"
142150
Then, you can access the `API_HOST` environment variable via the `env` parameter:
143151

144152
```python
145-
from workers import Response
153+
from workers import handler, Response
146154

155+
@handler
147156
async def on_fetch(request, env):
148157
return Response(env.API_HOST)
149158
```

0 commit comments

Comments
 (0)