The official SurrealDB SDK for Python.
Below is a quick guide on how to get started with SurrealDB in Python.
Before we can do anything, we need to download SurrealDB and start the server. See how to do that here
After we have everything up and running, we can install the Python SDK.
pip install surrealdb
Import the SDK and create the database connection:
from surrealdb import SurrealDB
db = SurrealDB("ws://localhost:8000/database/namespace")
Here, we can see that we defined the connection protocol as WebSocket using ws://
. We then defined the host as localhost
and the port as 8000
.
Finally, we defined the database and namespace as database
and namespace
.
We need a database and namespace to connect to SurrealDB.
Now that we have our connection we need to signin:
db.signin({
"username": "root",
"password": "root",
})
We can now run our queries to create some users, select them and print the outcome.
db.query("CREATE user:tobie SET name = 'Tobie';")
db.query("CREATE user:jaime SET name = 'Jaime';")
outcome = db.query("SELECT * FROM user;")
print(outcome)
The async methods work in the same way, with two main differences:
- Inclusion of
async def / await
. - You need to call the connect method before signing in.
import asyncio
from surrealdb import AsyncSurrealDB
async def main():
db = AsyncSurrealDB("ws://localhost:8000/database/namespace")
await db.connect()
await db.signin({
"username": "root",
"password": "root",
})
await db.query("CREATE user:tobie SET name = 'Tobie';")
await db.query("CREATE user:jaime SET name = 'Jaime';")
outcome = await db.query("SELECT * FROM user;")
print(outcome)
# Run the main function
asyncio.run(main())
The Python SDK currently only supports the AsyncSurrealDB
methods.