Query D1 from Python Workers
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.
Before getting started, you should:
- Review the D1 tutorial for TypeScript and JavaScript to learn how to create a D1 database and configure a Workers project.
- Refer to the Python language guide to understand how Python support works on the Workers platform.
- 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.
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.toml
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:
In your wrangler.toml
file, create a new [[d1_databases]]
configuration block and set database_name
and database_id
to the name and id (respectively) of the D1 database you want to query:
The value of binding
is how you will refer to your database from within your Worker. If you change this, you must change this in your Worker script as well.
To create a Python Worker, create an empty file at src/entry.py
, matching the value of main
in your wrangler.toml
file with the contents below:
The value of binding
in your wrangler.toml
file exactly must match the name of the variable in your Python code. This example refers to the database via a DB
binding, and query this binding via await env.DB.prepare(...)
.
You can then deploy your Python Worker directly:
Your Worker will be available at https://python-and-d1.YOUR_SUBDOMAIN.workers.dev
.
If you receive an error deploying:
- Make sure you have configured your
wrangler.toml
with thedatabase_id
anddatabase_name
of a valid D1 database. - Ensure
compatibility_flags = ["python_workers"]
is set in yourwrangler.toml
, which is required for Python. - Review the list of error codes, and ensure your code does not throw an uncaught exception.
- Refer to Workers Python documentation to learn more about how to use Python in Workers.
- Review the D1 client API and how to query D1 databases.
- Learn how to import data to your D1 database.