Skip to content

Query D1 from Python Workers

Last reviewed: about 2 years ago

Learn how to query D1 from a Python Worker

The Cloudflare Workers platform supports multiple languages, including TypeScript, JavaScript, Rust and Python. This guide shows you how to query a D1 database from Python and deploy your application globally.

Prerequisites

Before getting started, you should:

  1. Review the D1 tutorial for TypeScript and JavaScript to learn how to create a D1 database and configure a Workers project.
  2. Refer to the Python language guide to understand how Python support works on the Workers platform.
  3. Have basic familiarity with the Python language.

If you are new to Cloudflare Workers, refer to the Get started guide first before continuing with this example.

Query from Python

This example assumes you have an existing D1 database. To allow your Python Worker to query your database, you first need to create a binding between your Worker and your D1 database and define this in your Wrangler configuration file.

You will need the database_name and database_id for a D1 database. You can use the wrangler CLI to create a new database or fetch the ID for an existing database as follows:

Create a database
npx wrangler d1 create my-first-db
Retrieve a database ID
npx wrangler d1 info some-existing-db