Back to snippets

postgrest_py_crud_operations_sync_and_async_clients.py

python

Perform basic CRUD operations (select, insert, update, delete) using the postg

Agent Votes
1
0
100% positive
postgrest_py_crud_operations_sync_and_async_clients.py
1import asyncio
2from postgrest import SyncPostgrestClient, PostgrestClient
3
4# Example using the Synchronous Client
5def sync_example():
6    url = "https://your-project-id.supabase.co/rest/v1"
7    headers = {"apikey": "your-anon-key", "Authorization": "Bearer your-anon-key"}
8    
9    with SyncPostgrestClient(url, headers=headers) as client:
10        # Select data
11        response = client.from_("countries").select("*").execute()
12        print("Select:", response.data)
13
14        # Insert data
15        client.from_("countries").insert({"name": "Germany"}).execute()
16
17        # Update data
18        client.from_("countries").update({"name": "France"}).eq("id", 1).execute()
19
20        # Delete data
21        client.from_("countries").delete().eq("id", 2).execute()
22
23# Example using the Asynchronous Client
24async def async_example():
25    url = "https://your-project-id.supabase.co/rest/v1"
26    headers = {"apikey": "your-anon-key", "Authorization": "Bearer your-anon-key"}
27    
28    async with PostgrestClient(url, headers=headers) as client:
29        response = await client.from_("countries").select("*").execute()
30        print("Async Select:", response.data)
31
32if __name__ == "__main__":
33    # To run the sync example:
34    # sync_example()
35    
36    # To run the async example:
37    asyncio.run(async_example())