从 Python Workers 查询 D1

跳转到内容

Documentation Index
Fetch the complete documentation index at: /d1/llms.txt
Use this file to discover all available pages before exploring further.

从 Python Workers 查询 D1

了解如何从 Python Worker 查询 D1

最后更新:2026年9月17日|复制为 Markdown|查看 Markdown 原文|Agent setup

Cloudflare Workers 平台支持多种语言,包括 TypeScript、JavaScript、Rust 和 Python。本指南向你展示如何从 Python 查询 D1 数据库并在全球范围内部署你的应用程序。

前提条件

在开始之前,你应该:

  1. 查看适用于 TypeScript 和 JavaScript 的 D1 教程,了解如何创建 D1 数据库并配置 Workers 项目。
  2. 参阅 Python 语言指南,了解 Python 支持在 Workers 平台上的工作方式。
  3. 对 Python 语言有基本的熟悉。

如果你刚接触 Cloudflare Workers,请先参阅快速上手指南,然后再继续此示例。

从 Python 查询

此示例假设你已有一个现有的 D1 数据库。要允许你的 Python Worker 查询你的数据库,你首先需要在你的 Worker 和你的 D1 数据库之间创建一个绑定,并在你的 Wrangler 配置文件中定义它。

你将需要一个 D1 数据库的 database_name 和 database_id。你可以使用 wrangler CLI 创建新数据库或获取现有数据库的 ID,如下所示:

Create a databasesh

npx wrangler d1 create my-first-db

Retrieve a database IDsh

npx wrangler d1 info some-existing-db
# ┌───────────────────┬──────────────────────────────────────┐
# │                   │ c89db32e-83f4-4e62-8cd7-7c8f97659029 │
# ├───────────────────┼──────────────────────────────────────┤
# │ name              │ db-enam                              │
# ├───────────────────┼──────────────────────────────────────┤
# │ created_at        │ 2023-06-12T16:52:03.071Z             │
# └───────────────────┴──────────────────────────────────────┘

1. 配置绑定

在你的 Wrangler 文件中,创建一个新的 [[d1_databases]] 配置块,并将 database_name 和 database_id 分别设置为你想要查询的 D1 数据库的名称和 id:

{
	"$schema": "./node_modules/wrangler/config-schema.json",
	"name": "python-and-d1",
	"main": "src/entry.py",
	"compatibility_flags": [ // Required for Python Workers
		"python_workers"
	],
	// Set this to today's date
	"compatibility_date": "2026-10-13",
	"d1_databases": [
		{
			"binding": "DB", // This will be how you refer to your database in your Worker
			"database_name": "YOUR_DATABASE_NAME",
			"database_id": "YOUR_DATABASE_ID"
		}
	]
}
"$schema" = "./node_modules/wrangler/config-schema.json"
name = "python-and-d1"
main = "src/entry.py"
compatibility_flags = [ "python_workers" ]
# Set this to today's date
compatibility_date = "2026-10-13"

[[d1_databases]]
binding = "DB"
database_name = "YOUR_DATABASE_NAME"
database_id = "YOUR_DATABASE_ID"

binding 的值是你将在 Worker 内部引用数据库的方式。如果你更改它,你也必须在你的 Worker 脚本中更改它。

2. 创建你的 Python Worker

要创建 Python Worker,请在 src/entry.py 创建一个空文件,与你的 Wrangler 文件中 main 的值匹配,内容如下:

from workers import Response, WorkerEntrypoint

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        # Do anything else you'd like on request here!

        try:
            # Query D1 - we'll list all tables in our database in this example
            results = await self.env.DB.prepare("PRAGMA table_list").run()
            # Return a JSON response
            return Response.json(results)
        except Exception as e:
            return Response.json({"error": "Database query failed"}, status=500)

你的 Wrangler 文件中 binding 的值必须与你的 Python 代码中变量的名称完全匹配。此示例通过 DB 绑定引用数据库,并通过 await self.env.DB.prepare(...) 查询该绑定。

然后你可以直接部署你的 Python Worker:

npx wrangler deploy
# Example output
#
# Your worker has access to the following bindings:
# - D1 Databases:
#   - DB: db-enam (c89db32e-83f4-4e62-8cd7-7c8f97659029)
# Total Upload: 0.18 KiB / gzip: 0.17 KiB
# Uploaded python-and-d1 (4.93 sec)
# Published python-and-d1 (0.51 sec)
#   https://python-and-d1.YOUR_SUBDOMAIN.workers.dev
# Current Deployment ID: 80b72e19-da82-4465-83a2-c12fb11ccc72

你的 Worker 将在 https://python-and-d1.YOUR_SUBDOMAIN.workers.dev 可用。

如果你在部署时收到错误:

  • 确保你已使用有效 D1 数据库的 database_id 和 database_name 配置了你的 Wrangler 配置文件。
  • 确保在你的 Wrangler 配置文件中设置了 compatibility_flags = ["python_workers"],这是 Python 所必需的。
  • 查看错误代码列表,并确保你的代码不会抛出未捕获的异常。

后续步骤