Skip to content

Commit 660337a

Browse files
query d1 (#14)
* query d1 first commit * changes for merge from comments * deleted files
1 parent 1e9aa95 commit 660337a

3 files changed

Lines changed: 46 additions & 0 deletions

File tree

05-query-d1/README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Query a D1 Database with Cloudflare Workers Example
2+
3+
Warning: Python support in Workers is experimental and things will break. This demo is meant for reference only right now; you should be prepared to update your code between now and official release time as APIs may change.
4+
5+
Currently, Python Workers using packages cannot be deployed and will only work in local development for the time being.
6+
7+
### How to Run
8+
Download this quotes file from [Hugging Face in SQL form](https://huggingface.co/datasets/lizziepika/quotes_sql/blob/main/data.sql)
9+
10+
Create a new D1 database by running on the command line `npx wrangler d1 create {D1-NAME}`. Copy and paste the output into your `wrangler.toml` to bind your D1 database to your Python Worker.
11+
12+
Ensure that your Wrangler version is up to date (3.30.0 and above).
13+
14+
```
15+
$ wrangler -v
16+
⛅️ wrangler 3.30.0
17+
```
18+
Now, if you run `wrangler dev` within this directory, it should use the config in`wrangler.toml` to run the demo.
19+
20+
You can also run `wrangler deploy` to deploy the demo.
21+
22+
Finally, get a random quote from the database by visiting your deployed worker in the browser!<img width="1421" alt="deployed app" src="https://github.com/user-attachments/assets/131a2836-2305-4b73-a54a-50dac039108f">

05-query-d1/src/entry.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
from js import Response
2+
3+
async def on_fetch(request, env):
4+
query = """
5+
SELECT quote, author
6+
FROM qtable
7+
ORDER BY RANDOM()
8+
LIMIT 1;
9+
"""
10+
results = await env.DB.prepare(query).all()
11+
data = results.results[0]
12+
13+
# Return a JSON response
14+
return Response.json(data)

05-query-d1/wrangler.toml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#:schema node_modules/wrangler/config-schema.json
2+
compatibility_date = "2024-08-06"
3+
4+
[ai]
5+
binding = "AI"
6+
7+
[[d1_databases]]
8+
binding = "DB" # i.e. available in your Worker on env.DB
9+
database_name = "quotes" # REPLACE WITH YOUR DB NAME
10+
database_id = "408cddb7-e3f7-40d7-a4f7-33136a7fd3fa" # REPLACE WITH YOUR DB ID

0 commit comments

Comments
 (0)