surrealdb


Namesurrealdb JSON
Version 0.4.1 PyPI version JSON
download
home_pagehttps://github.com/surrealdb/surrealdb.py
SummaryThe official SurrealDB library for Python.
upload_time2024-12-02 08:01:53
maintainerNone
docs_urlNone
authorSurrealDB
requires_python<4.0,>=3.10
licenseApache-2.0
keywords surrealdb database
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <br>

<p align="center">
	<img width=120 src="https://raw.githubusercontent.com/surrealdb/icons/main/surreal.svg" />
	&nbsp;
	<img width=120 src="https://raw.githubusercontent.com/surrealdb/icons/main/python.svg" />
</p>

<h3 align="center">The official SurrealDB SDK for Python.</h3>

<br>

<p align="center">
	<a href="https://github.com/surrealdb/surrealdb.py"><img src="https://img.shields.io/badge/status-beta-ff00bb.svg?style=flat-square"></a>
	&nbsp;
	<a href="https://surrealdb.com/docs/integration/libraries/javascript"><img src="https://img.shields.io/badge/docs-view-44cc11.svg?style=flat-square"></a>
	&nbsp;
	<a href="https://pypi.org/project/surrealdb/"><img src="https://img.shields.io/pypi/v/surrealdb?style=flat-square"></a>
    &nbsp;
    <a href="https://pypi.org/project/surrealdb/"><img src="https://img.shields.io/pypi/dm/surrealdb?style=flat-square"></a>    
	&nbsp;
	<a href="https://pypi.org/project/surrealdb/"><img src="https://img.shields.io/pypi/pyversions/surrealdb?style=flat-square"></a>
</p>

<p align="center">
	<a href="https://surrealdb.com/discord"><img src="https://img.shields.io/discord/902568124350599239?label=discord&style=flat-square&color=5a66f6"></a>
	&nbsp;
    <a href="https://twitter.com/surrealdb"><img src="https://img.shields.io/badge/twitter-follow_us-1d9bf0.svg?style=flat-square"></a>
    &nbsp;
    <a href="https://www.linkedin.com/company/surrealdb/"><img src="https://img.shields.io/badge/linkedin-connect_with_us-0a66c2.svg?style=flat-square"></a>
    &nbsp;
    <a href="https://www.youtube.com/channel/UCjf2teVEuYVvvVC-gFZNq6w"><img src="https://img.shields.io/badge/youtube-subscribe-fc1c1c.svg?style=flat-square"></a>
</p>

# surrealdb.py

The official SurrealDB SDK for Python.

## Documentation

View the SDK documentation [here](https://surrealdb.com/docs/integration/libraries/python).

## How to install

```sh
pip install surrealdb
```

## Basic Usage
> All examples assume SurrealDB is [installed](https://surrealdb.com/install) 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.
```python
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.
```python
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 
```python
from surrealdb import AsyncSurrealDB

async with AsyncSurrealDB(url="ws://localhost:8080") as db:
    await db.use("namespace", "database_name")
```
Without context manager:
```python
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
```python
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
```python
from surrealdb import SurrealDB

db = SurrealDB("surrealkv://path/to/dbfile.kv")
```
For Memory
```python
from surrealdb import SurrealDB

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

## Additional Examples
### Insert and Retrieve Data
```python
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
```python
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
```python
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
```python
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
```python
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.


            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/surrealdb/surrealdb.py",
    "name": "surrealdb",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.10",
    "maintainer_email": null,
    "keywords": "SurrealDB, Database",
    "author": "SurrealDB",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/63/1c/e2d1e17be08126df6e1265d6a26ac7982bd01fade0d328fb5164d7821fe7/surrealdb-0.4.1.tar.gz",
    "platform": null,
    "description": "<br>\n\n<p align=\"center\">\n\t<img width=120 src=\"https://raw.githubusercontent.com/surrealdb/icons/main/surreal.svg\" />\n\t&nbsp;\n\t<img width=120 src=\"https://raw.githubusercontent.com/surrealdb/icons/main/python.svg\" />\n</p>\n\n<h3 align=\"center\">The official SurrealDB SDK for Python.</h3>\n\n<br>\n\n<p align=\"center\">\n\t<a href=\"https://github.com/surrealdb/surrealdb.py\"><img src=\"https://img.shields.io/badge/status-beta-ff00bb.svg?style=flat-square\"></a>\n\t&nbsp;\n\t<a href=\"https://surrealdb.com/docs/integration/libraries/javascript\"><img src=\"https://img.shields.io/badge/docs-view-44cc11.svg?style=flat-square\"></a>\n\t&nbsp;\n\t<a href=\"https://pypi.org/project/surrealdb/\"><img src=\"https://img.shields.io/pypi/v/surrealdb?style=flat-square\"></a>\n    &nbsp;\n    <a href=\"https://pypi.org/project/surrealdb/\"><img src=\"https://img.shields.io/pypi/dm/surrealdb?style=flat-square\"></a>    \n\t&nbsp;\n\t<a href=\"https://pypi.org/project/surrealdb/\"><img src=\"https://img.shields.io/pypi/pyversions/surrealdb?style=flat-square\"></a>\n</p>\n\n<p align=\"center\">\n\t<a href=\"https://surrealdb.com/discord\"><img src=\"https://img.shields.io/discord/902568124350599239?label=discord&style=flat-square&color=5a66f6\"></a>\n\t&nbsp;\n    <a href=\"https://twitter.com/surrealdb\"><img src=\"https://img.shields.io/badge/twitter-follow_us-1d9bf0.svg?style=flat-square\"></a>\n    &nbsp;\n    <a href=\"https://www.linkedin.com/company/surrealdb/\"><img src=\"https://img.shields.io/badge/linkedin-connect_with_us-0a66c2.svg?style=flat-square\"></a>\n    &nbsp;\n    <a href=\"https://www.youtube.com/channel/UCjf2teVEuYVvvVC-gFZNq6w\"><img src=\"https://img.shields.io/badge/youtube-subscribe-fc1c1c.svg?style=flat-square\"></a>\n</p>\n\n# surrealdb.py\n\nThe official SurrealDB SDK for Python.\n\n## Documentation\n\nView the SDK documentation [here](https://surrealdb.com/docs/integration/libraries/python).\n\n## How to install\n\n```sh\npip install surrealdb\n```\n\n## Basic Usage\n> All examples assume SurrealDB is [installed](https://surrealdb.com/install) and running on port 8000.\n### Initialization\nTo start using the database, create an instance of SurrealDB, connect to your SurrealDB server, and specify the\nnamespace and database you wish to work with.\n```python\nfrom surrealdb import SurrealDB\n\n# Connect to the database\ndb = SurrealDB(url=\"ws://localhost:8080\")\ndb.connect()\ndb.use(\"namespace\", \"database_name\")\n```\n\n### Using context manager\nThe library supports Python\u2019s context manager to manage connections automatically. \nThis ensures that connections are properly closed when the block of code finishes executing.\n```python\nfrom surrealdb import SurrealDB\n\nwith SurrealDB(url=\"ws://localhost:8080\") as db:\n    db.use(\"namespace\", \"database_name\")\n```\n\n### Using Async\nThe AsyncSurrealDB supports asynchronous operations while retaining compatibility with synchronous workflows, \nensuring flexibility for any range of use cases. The APIs do not differ \n```python\nfrom surrealdb import AsyncSurrealDB\n\nasync with AsyncSurrealDB(url=\"ws://localhost:8080\") as db:\n    await db.use(\"namespace\", \"database_name\")\n```\nWithout context manager:\n```python\nfrom surrealdb import AsyncSurrealDB\n\n# Connect to the database\ndb = AsyncSurrealDB(url=\"ws://localhost:8080\")\nawait db.connect()\nawait db.use(\"namespace\", \"database_name\")\n```\n\n### Example Usage\n```python\nfrom surrealdb import SurrealDB, GeometryPoint, Table\n\nwith SurrealDB(url=\"ws://localhost:8000\") as db:\n    db.use(\"test_ns\", \"test_db\")\n    auth_token = db.sign_in(username=\"root\", password=\"root\")\n\n    # Check token validity. This is not necessary if you called `sign_in` before. This authenticates the\n    # `db` instance too if `sign_in` was not previously called\n    db.authenticate(auth_token)\n\n    # Create an entry\n    person = db.create(Table(\"persons\"), {\n        \"Name\": \"John\",\n        \"Surname\": \"Doe\",\n        \"Location\": GeometryPoint(-0.11, 22.00),\n    })\n\n    print(\"Created person with a map:\", person)\n\n    # Get entry by Record ID\n    person = db.select(person.get(\"id\"))\n    print(\"Selected a person by record id: \", person)\n\n    # Or retrieve the entire table\n    persons = db.select(Table(\"persons\"))\n    print(\"Selected all in persons table: \", persons)\n\n    # Delete an entry by ID\n    _ = db.delete(persons[0].get(\"id\"))\n\n    # Delete all entries\n    _ = db.delete(Table(\"persons\"))\n\n    # Confirm empty table\n    persons = db.select(Table(\"persons\"))\n    print(\"No Selected person: \", persons)\n\n    # And later, we can invalidate the token\n    db.invalidate(auth_token)\n```\n\n## Connection Engines\nThere are 3 available connection engines you can use to connect to SurrealDb backend. It can be via Websocket, HTTP or\nthrough embedded database connections. The connection types are simply determined by the url scheme provided in \nthe connection url.\n\n### Via Websocket\nWebsocket url can be `ws` or `wss` for secure connection. For example `ws://localhost:8000` and `wss://localhost:8000`.\nAll functionalities are available via websockets.\n\n### Via HTTP\nHTTP url can be `http` or `https` for secure connection. For example `http://localhost:8000` and `https://localhost:8000`.\nThere are some functions that are not available on RPC when using HTTP but are on Websocket. This includes all \nlive query/notification methods.\n\n\n### Using SurrealKV and Memory\nSurrealKV and In-Memory also do not support live notifications at this time. This would be updated in a later \nrelease.\n\nFor Surreal KV\n```python\nfrom surrealdb import SurrealDB\n\ndb = SurrealDB(\"surrealkv://path/to/dbfile.kv\")\n```\nFor Memory\n```python\nfrom surrealdb import SurrealDB\n\ndb = SurrealDB(\"mem://\")\ndb = SurrealDB(\"memory://\")\n```\n\n## Additional Examples\n### Insert and Retrieve Data\n```python\nfrom surrealdb import SurrealDB\n\ndb = SurrealDB(\"ws://localhost:8000\")\ndb.connect()\ndb.use(\"example_ns\", \"example_db\")\ndb.sign_in(\"root\", \"root\")\n\n# Insert a record\nnew_user = {\"name\": \"Alice\", \"age\": 30}\ninserted_record = db.insert(\"users\", new_user)\nprint(f\"Inserted Record: {inserted_record}\")\n\n# Retrieve the record\nretrieved_users = db.select(\"users\")\nprint(f\"Retrieved Users: {retrieved_users}\")\n\ndb.close()\n```\n\n### Perform a Custom Query\n```python\nfrom surrealdb import AsyncSurrealDB\n\nasync def main():\n    async with AsyncSurrealDB(url=\"ws://localhost:8000\") as db:\n        await db.sign_in(\"root\", \"root\")\n        await db.use(\"test\", \"test\")\n\n        query = \"SELECT * FROM users WHERE age > min_age;\"\n        variables = {\"min_age\": 25}\n\n        results = await db.query(query, variables)\n        print(f\"Query Results: {results}\")\n\nasyncio.run(main())\n```\n\n### Manage Authentication\n```python\nfrom surrealdb import SurrealDB\n\nwith SurrealDB(url=\"ws://localhost:8080\") as db:\n    # Sign up a new user\n    token = db.sign_up(username=\"new_user\", password=\"secure_password\")\n    print(f\"New User Token: {token}\")\n    \n    # Sign in as an existing user\n    token = db.sign_in(username=\"existing_user\", password=\"secure_password\")\n    print(f\"Signed In Token: {token}\")\n    \n    # Authenticate using a token\n    db.authenticate(token=token)\n    print(\"Authentication successful!\")\n```\n\n### Live Query Notifications\n```python\nimport asyncio\nfrom surrealdb.surrealdb import SurrealDB\n\ndb = SurrealDB(\"ws://localhost:8080\")\ndb.connect()\ndb.use(\"example_ns\", \"example_db\")\n\n# Start a live query\nlive_id = db.live(\"users\")\n\n# Process live notifications\nnotifications = db.live_notifications(live_id)\n\nasync def handle_notifications():\n    while True:\n        notification = await notifications.get()\n        print(f\"Live Notification: {notification}\")\n\n# Run the notification handler\nasyncio.run(handle_notifications())\n```\n\n### Upserting Records\n```python\nfrom surrealdb.surrealdb import SurrealDB\n\nwith SurrealDB(\"ws://localhost:8000\") as db:\n    db.sign_in(\"root\", \"root\")\n    db.use(\"example_ns\", \"example_db\")\n\n    upsert_data = { \"name\": \"Charlie\", \"age\": 35}\n    result = db.upsert(\"users\", upsert_data)\n    print(f\"Upsert Result: {result}\")\n```\n\n## Contributing\nContributions to this library are welcome! If you encounter issues, have feature requests, or \nwant to make improvements, feel free to open issues or submit pull requests.\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "The official SurrealDB library for Python.",
    "version": "0.4.1",
    "project_urls": {
        "Documentation": "https://surrealdb.com/docs/sdk/python",
        "Homepage": "https://github.com/surrealdb/surrealdb.py",
        "Repository": "https://github.com/surrealdb/surrealdb.py"
    },
    "split_keywords": [
        "surrealdb",
        " database"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "063e4f608ca4747b62339cc77d709e9d123ae9d7fbeed6c4f2fc273e8d2f5208",
                "md5": "6df508d015cec9b0f2020b88982d84e7",
                "sha256": "f49f59992575886cbf8137819ad6aa4df4c2a0e23824742fde8c8dcd822f58f4"
            },
            "downloads": -1,
            "filename": "surrealdb-0.4.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "6df508d015cec9b0f2020b88982d84e7",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.10",
            "size": 26902,
            "upload_time": "2024-12-02T08:01:52",
            "upload_time_iso_8601": "2024-12-02T08:01:52.772500Z",
            "url": "https://files.pythonhosted.org/packages/06/3e/4f608ca4747b62339cc77d709e9d123ae9d7fbeed6c4f2fc273e8d2f5208/surrealdb-0.4.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "631ce2d1e17be08126df6e1265d6a26ac7982bd01fade0d328fb5164d7821fe7",
                "md5": "b07fba32ffaa304f2c531b6ebf4abbcb",
                "sha256": "3ce1ad585a6ee199e376c2c426cc7978bc8d8bdb564da312244ab13b4f18f186"
            },
            "downloads": -1,
            "filename": "surrealdb-0.4.1.tar.gz",
            "has_sig": false,
            "md5_digest": "b07fba32ffaa304f2c531b6ebf4abbcb",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.10",
            "size": 23138,
            "upload_time": "2024-12-02T08:01:53",
            "upload_time_iso_8601": "2024-12-02T08:01:53.896740Z",
            "url": "https://files.pythonhosted.org/packages/63/1c/e2d1e17be08126df6e1265d6a26ac7982bd01fade0d328fb5164d7821fe7/surrealdb-0.4.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-02 08:01:53",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "surrealdb",
    "github_project": "surrealdb.py",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "surrealdb"
}
        
Elapsed time: 4.96108s