You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/docs/workers/languages/python/index.mdx
+14-5Lines changed: 14 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -38,17 +38,23 @@ cd python-workers-examples/01-hello
38
38
npx wrangler@latest dev
39
39
```
40
40
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:
42
42
43
43
```python
44
-
from workers import Response
44
+
from workers importhandler, Response
45
45
46
+
@handler
46
47
defon_fetch(request):
47
48
return Response("Hello World!")
48
49
```
49
50
50
51
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`.
51
52
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
+
52
58
To run a Python Worker locally, you use [Wrangler](/workers/wrangler/), the CLI for Cloudflare Workers:
53
59
54
60
```bash
@@ -74,8 +80,9 @@ Now, we can modify `src/entry.py` to make use of the new module.
74
80
75
81
```python
76
82
from hello import hello
77
-
from workers import Response
83
+
from workers importhandler, Response
78
84
85
+
@handler
79
86
defon_fetch(request):
80
87
return Response(hello("World"))
81
88
```
@@ -93,9 +100,10 @@ Let's try editing the worker to accept a POST request. We know from the
93
100
JSON. In a Python Worker, you would write:
94
101
95
102
```python
96
-
from workers import Response
103
+
from workers importhandler, Response
97
104
from hello import hello
98
105
106
+
@handler
99
107
asyncdefon_fetch(request):
100
108
name = (await request.json())["name"]
101
109
return Response(hello(name))
@@ -142,8 +150,9 @@ API_HOST = "example.com"
142
150
Then, you can access the `API_HOST` environment variable via the `env` parameter:
0 commit comments