Skip to main content

The official SurrealDB library for Python.

Project description


 

The official SurrealDB SDK for Python.


       

     

surrealdb.py

The official SurrealDB SDK for Python.

Documentation

View the SDK documentation here.

How to install

pip install surrealdb

Basic Usage

All examples assume SurrealDB is installed and running on port 8000.

Initialization

To start using the database, create an instance of SurrealDB, connect to your SurrealDB server, and specify the namespace and database you wish to work with.

from surrealdb import SurrealDB

# Connect to the database
db = SurrealDB(url="ws://localhost:8080")
db.connect()
db.use("namespace", "database_name")

Using context manager

The library supports Python’s context manager to manage connections automatically. This ensures that connections are properly closed when the block of code finishes executing.

from surrealdb import SurrealDB

with SurrealDB(url="ws://localhost:8080") as db:
    db.use("namespace", "database_name")

Using Async

The AsyncSurrealDB supports asynchronous operations while retaining compatibility with synchronous workflows, ensuring flexibility for any range of use cases. The APIs do not differ

from surrealdb import AsyncSurrealDB

async with AsyncSurrealDB(url="ws://localhost:8080") as db:
    await db.use("namespace", "database_name")

Without context manager:

from surrealdb import AsyncSurrealDB

# Connect to the database
db = AsyncSurrealDB(url="ws://localhost:8080")
await db.connect()
await db.use("namespace", "database_name")

Example Usage

from surrealdb import SurrealDB, GeometryPoint, Table

with SurrealDB(url="ws://localhost:8000") as db:
    db.use("test_ns", "test_db")
    auth_token = db.sign_in(username="root", password="root")

    # Check token validity. This is not necessary if you called `sign_in` before. This authenticates the
    # `db` instance too if `sign_in` was not previously called
    db.authenticate(auth_token)

    # Create an entry
    person = db.create(Table("persons"), {
        "Name": "John",
        "Surname": "Doe",
        "Location": GeometryPoint(-0.11, 22.00),
    })

    print("Created person with a map:", person)

    # Get entry by Record ID
    person = db.select(person.get("id"))
    print("Selected a person by record id: ", person)

    # Or retrieve the entire table
    persons = db.select(Table("persons"))
    print("Selected all in persons table: ", persons)

    # Delete an entry by ID
    _ = db.delete(persons[0].get("id"))

    # Delete all entries
    _ = db.delete(Table("persons"))

    # Confirm empty table
    persons = db.select(Table("persons"))
    print("No Selected person: ", persons)

    # And later, we can invalidate the token
    db.invalidate(auth_token)

Connection Engines

There are 3 available connection engines you can use to connect to SurrealDb backend. It can be via Websocket, HTTP or through embedded database connections. The connection types are simply determined by the url scheme provided in the connection url.

Via Websocket

Websocket url can be ws or wss for secure connection. For example ws://localhost:8000 and wss://localhost:8000. All functionalities are available via websockets.

Via HTTP

HTTP url can be http or https for secure connection. For example http://localhost:8000 and https://localhost:8000. There are some functions that are not available on RPC when using HTTP but are on Websocket. This includes all live query/notification methods.

Using SurrealKV and Memory

SurrealKV and In-Memory also do not support live notifications at this time. This would be updated in a later release.

For Surreal KV

from surrealdb import SurrealDB

db = SurrealDB("surrealkv://path/to/dbfile.kv")

For Memory

from surrealdb import SurrealDB

db = SurrealDB("mem://")
db = SurrealDB("memory://")

Additional Examples

Insert and Retrieve Data

from surrealdb import SurrealDB

db = SurrealDB("ws://localhost:8000")
db.connect()
db.use("example_ns", "example_db")
db.sign_in("root", "root")

# Insert a record
new_user = {"name": "Alice", "age": 30}
inserted_record = db.insert("users", new_user)
print(f"Inserted Record: {inserted_record}")

# Retrieve the record
retrieved_users = db.select("users")
print(f"Retrieved Users: {retrieved_users}")

db.close()

Perform a Custom Query

from surrealdb import AsyncSurrealDB

async def main():
    async with AsyncSurrealDB(url="ws://localhost:8000") as db:
        await db.sign_in("root", "root")
        await db.use("test", "test")

        query = "SELECT * FROM users WHERE age > min_age;"
        variables = {"min_age": 25}

        results = await db.query(query, variables)
        print(f"Query Results: {results}")

asyncio.run(main())

Manage Authentication

from surrealdb import SurrealDB

with SurrealDB(url="ws://localhost:8080") as db:
    # Sign up a new user
    token = db.sign_up(username="new_user", password="secure_password")
    print(f"New User Token: {token}")
    
    # Sign in as an existing user
    token = db.sign_in(username="existing_user", password="secure_password")
    print(f"Signed In Token: {token}")
    
    # Authenticate using a token
    db.authenticate(token=token)
    print("Authentication successful!")

Live Query Notifications

import asyncio
from surrealdb.surrealdb import SurrealDB

db = SurrealDB("ws://localhost:8080")
db.connect()
db.use("example_ns", "example_db")

# Start a live query
live_id = db.live("users")

# Process live notifications
notifications = db.live_notifications(live_id)

async def handle_notifications():
    while True:
        notification = await notifications.get()
        print(f"Live Notification: {notification}")

# Run the notification handler
asyncio.run(handle_notifications())

Upserting Records

from surrealdb.surrealdb import SurrealDB

with SurrealDB("ws://localhost:8000") as db:
    db.sign_in("root", "root")
    db.use("example_ns", "example_db")

    upsert_data = { "name": "Charlie", "age": 35}
    result = db.upsert("users", upsert_data)
    print(f"Upsert Result: {result}")

Contributing

Contributions to this library are welcome! If you encounter issues, have feature requests, or want to make improvements, feel free to open issues or submit pull requests.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

surrealdb-0.4.1.tar.gz (23.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

surrealdb-0.4.1-py3-none-any.whl (26.9 kB view details)

Uploaded Python 3

File details

Details for the file surrealdb-0.4.1.tar.gz.

File metadata

  • Download URL: surrealdb-0.4.1.tar.gz
  • Upload date:
  • Size: 23.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.13.0 Darwin/24.0.0

File hashes

Hashes for surrealdb-0.4.1.tar.gz
Algorithm Hash digest
SHA256 3ce1ad585a6ee199e376c2c426cc7978bc8d8bdb564da312244ab13b4f18f186
MD5 b07fba32ffaa304f2c531b6ebf4abbcb
BLAKE2b-256 631ce2d1e17be08126df6e1265d6a26ac7982bd01fade0d328fb5164d7821fe7

See more details on using hashes here.

File details

Details for the file surrealdb-0.4.1-py3-none-any.whl.

File metadata

  • Download URL: surrealdb-0.4.1-py3-none-any.whl
  • Upload date:
  • Size: 26.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.4 CPython/3.13.0 Darwin/24.0.0

File hashes

Hashes for surrealdb-0.4.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f49f59992575886cbf8137819ad6aa4df4c2a0e23824742fde8c8dcd822f58f4
MD5 6df508d015cec9b0f2020b88982d84e7
BLAKE2b-256 063e4f608ca4747b62339cc77d709e9d123ae9d7fbeed6c4f2fc273e8d2f5208

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page