INTEGRITY Dokumentace

Příklady

Cloudflare nabízí širokou škálu příkladů v Pythonu v Galerie příkladů Workers.

Kromě těchto příkladů si prohlédněte i následující, které ukazují chování specifické pro Python.

Moduly ve vašem Workeru

Řekněme, že váš Worker má následující strukturu:

├── src
│   ├── module.py
│   └── main.py
├── uv.lock
├── pyproject.toml
└── wrangler.toml

Chcete-li importovat module.py v main.py, použili byste následující import:

import module

V tomto případě je hlavní modul nastaven na src/main.py v souboru wrangler.toml takto:

main = "src/main.py"

To znamená, že src adresář není nutné uvádět v příkazu importu.

Parsuje URL příchozího požadavku

from workers import WorkerEntrypoint, Response
from urllib.parse import urlparse, parse_qs

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        # 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])
            return Response(greeting)


        if url.path == "/favicon.ico":
          return Response("")

        return Response("Hello world!")

Parsuje JSON z příchozího požadavku

from workers import WorkerEntrypoint, Response

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        body = await request.json()  # returns a native Python dict
        name = body["name"]
        return Response("Hello, {name}".format(name=name))

Vraťte odpověď JSON

from workers import WorkerEntrypoint, Response

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        data = {"greeting": "Hello, World!", "status": "ok"}
        return Response.json(data)

Čtení sloučených souborů assets ve vašem Workeru

Řekněme, že váš Worker má následující strukturu:

├── src
│   ├── file.html
│   └── main.py
└── wrangler.jsonc

Chcete-li přečíst soubor ve svém Workeru, postupujte takto:

from pathlib import Path
from workers import WorkerEntrypoint, Response

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        html_file = Path(__file__).parent / "file.html"
        return Response(html_file.read_text(), headers={"Content-Type": "text/html"})

Odesílání logů z vašeho Python Workeru

# To use the JavaScript console APIs
from js import console
from workers import WorkerEntrypoint, Response
# To use the native Python logging
import logging

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        # Use the console APIs from JavaScript
        # https://developer.mozilla.org/en-US/docs/Web/API/console
        console.log("console.log from Python!")

        # Alternatively, use the native Python logger
        logger = logging.getLogger(__name__)

        # The default level is warning. We can change that to info.
        logging.basicConfig(level=logging.INFO)

        logger.error("error from Python!")
        logger.info("info log from Python!")

        # Or just use print()
        print("print() from Python!")

        return Response("We're testing logging!")

Publikování do Queue

from workers import WorkerEntrypoint, Response

class Default(WorkerEntrypoint):
    async def fetch(self, request):
			  # Bindings are available on the 'env' attribute
        # https://developers.cloudflare.com/queues/

        # The default contentType is "json"
        # We can also pass plain text strings
        await self.env.QUEUE.send("hello", contentType="text")
        # Send a JSON payload
        await self.env.QUEUE.send({"hello": "world"})

        return Response.json({"write": "success"})

Dotazování databáze D1

from workers import WorkerEntrypoint, Response

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        results = await self.env.DB.prepare("PRAGMA table_list").run()
        # Return a JSON response
        return Response.json(results)

Viz Dotazování D1 z Python Workers pro podrobnější návod, který popisuje, jak vytvořit novou databázi D1 a nakonfigurovat vazby na D1.

Durable Object

from workers import WorkerEntrypoint, Response, DurableObject

class List(DurableObject):
    async def get_messages(self):
        messages = await self.ctx.storage.get("messages")
        return messages if messages else []

    async def add_message(self, message):
        messages = await self.get_messages()
        messages.append(message)
        await self.ctx.storage.put("messages", messages)
        return

    async def say_hello(self):
        result = self.ctx.storage.sql.exec(
            "SELECT 'Hello, World!' as greeting"
        ).one()

        return result.greeting

Viz Dokumentace Durable Objects s dalšími informacemi.

Cron Trigger

from workers import WorkerEntrypoint

class Default(WorkerEntrypoint):
    async def scheduled(self, controller, env, ctx):
        # All four parameters (self, controller, env, ctx) are required —
        # unlike fetch() which only takes (self, request).
        print("cron processed")

Viz Dokumentace Cron Triggers s dalšími informacemi.

Workflows

from workers import WorkflowEntrypoint

class MyWorkflow(WorkflowEntrypoint):
    async def run(self, event, step):
        @step.do()
        async def step_a():
            # do some work
            return 10

        @step.do()
        async def step_b():
            # do some work
            return 20

        @step.do(concurrent=True)
        async def my_final_step(step_a, step_b):
            # should return 30
            return step_a + step_b

        await my_final_step()

Viz Dokumentace k Python Workflows s dalšími informacemi.

Další příklady

Nebo můžete naklonovat repozitář s příklady kde najdete ještě více příkladů:

git clone https://github.com/cloudflare/python-workers-examples