python-convex db query
How can I query the convex database in Convex? I'd like to grab a row and column from a table with my pk matching, how can I do that in python?
1 Reply
@Mac hi try this.
To query the Convex database from Python and retrieve a specific row and column based on a primary key (pk), you can follow these steps:
1. Define a Query Function in Convex: First, you’ll need to create a query function within your Convex application that can fetch data based on the pk. This function will be exposed via Convex’s HTTP API.
2. Call the Function from Python: Use Python’s requests library to make an HTTP POST request to the Convex function you defined, passing the necessary parameters.
Below is a step-by-step guide to achieve this:
Step 1: Define a Query Function in Convex
Create a new query function in your Convex functions directory (e.g., convex/functions/get_row_by_pk.js):
// convex/functions/get_row_by_pk.js
import { query } from "./_generated/server";
export default query(async ({ db }, { tableName, pk, columnName }) => {
// Fetch the item with the specified primary key
const item = await db.table(tableName).get(pk);
if (!item) {
throw new Error("Item not found");
}
// Return the specific column value if columnName is provided
if (columnName) {
return { [columnName]: item[columnName] };
}
// Return the entire item if columnName is not provided
return item;
});
Parameters:
• tableName: The name of the table you want to query.
• pk: The primary key value of the row you want to retrieve.
• columnName (optional): The specific column you want to retrieve from the row.
Step 2: Expose the Function via Convex’s HTTP API
Ensure that your Convex deployment is set up to allow HTTP function calls. Convex functions are accessible via HTTP endpoints in the format:
POST https://<your-convex-deployment>.convex.cloud/api/functions/<functionName>
Step 3: Call the Convex Function from Python
Use Python’s requests library to make a POST request to your Convex function:
import requests
# Replace with your Convex deployment URL
CONVEX_URL = 'https://your-convex-deployment.convex.cloud'
# The name of the function you defined in Convex
FUNCTION_NAME = 'get_row_by_pk'
# Parameters to pass to the Convex function
params = {
'tableName': 'your_table_name',
'pk': 'your_primary_key_value',
'columnName': 'your_column_name' # Optional
}
# Make a POST request to the Convex function
response = requests.post(
f'{CONVEX_URL}/api/functions/{FUNCTION_NAME}',
json=params
)
# Handle the response
if response.status_code == 200:
data = response.json()
print("Retrieved Data:", data)
else:
print(f'Error {response.status_code}: {response.text}')