A session object runs requests in one session on the server, with its own namespace, database, variables and sign-in, over the WebSocket connection that created it. This page lists the properties and methods of BlockingSurrealSession, which a blocking connection returns, and AsyncSurrealSession, which an asynchronous connection returns. See Multiple sessions for how to use them.
Sessions need a WebSocket connection (ws:// or wss://) and SurrealDB 3.0 or later. On an HTTP or embedded connection, new_session() raises UnsupportedFeatureError. Against SurrealDB 2.x, it raises UnavailableFeatureError.
Source: async_ws.py · blocking_ws.py
Creating a session
session = db.new_session()Returns: a BlockingSurrealSession on a blocking connection, or an AsyncSurrealSession on an asynchronous connection
new_session() starts a session that is signed in as the user of the connection, with no namespace, database or variables. Two other methods start a session as a copy of an existing one: fork() on a session, and fork_session() on the connection.
from surrealdb import Surreal
db = Surreal("ws://localhost:8000")
db.connect()
db.signin({"username": "root", "password": "secret"})
session = db.new_session()
session.use("surrealdb", "reports")Properties
.id
The UUID of the session on the server. db.sessions() lists the same ids, and the connection methods that take a session_id keyword accept it.
.server_version
The version that the server reported when the connection opened, such as "4.0.0". It is the same value as the server_version of the connection.
Inherited methods
A session has the query, data, authentication and variable methods of the connection. Each one runs in the session, with its namespace, database, variables and sign-in. The links lead to the full description of each method in the Surreal reference.
On an AsyncSurrealSession, await each method. The methods that return a builder return one that runs when you await it.
| Method | Returns on BlockingSurrealSession | Description |
|---|---|---|
.use(namespace, database) | None | Select a namespace, a database, or both, for the session. |
.query(query, vars) | SyncQueryBuilder | Run SurrealQL. .execute() gives one result for each statement, and .first() gives the result of the first statement. |
.query_raw(query, vars) | dict | Run SurrealQL and return the response with the status of each statement. |
.batch() | Batch | Collect statements to send as one transaction in one request. |
.run(name, args, version) | Value | Call a SurrealDB function. |
.select(record, fields, into) | SyncCrudBuilder | Select a record, a range of records or a table. |
.create(record, data, into) | The record, or a builder when called without data | Create a record. |
.update(record, data, into) | The result, or a builder when called without data | Replace the content of records, or chain .merge(), .patch() or .replace(). |
.upsert(record, data, into) | The result, or a builder when called without data | Create or update records. |
.delete(record, into) | SyncCrudBuilder | Delete records. |
.insert(table, data, into, relation) | A list of records, or a builder when called without data | Insert records. relation=True inserts relations. |
.relate(from_, edge, to, data) | The edge, or a builder when called without data | Relate records through an edge table. |
.signin(vars) | Tokens | Sign the session in. |
.signup(vars) | Tokens | Sign up a record user and sign the session in as that user. |
.authenticate(token) | None | Authenticate the session with an access token. |
.refresh(tokens) | Tokens | Exchange the refresh token of the session for a new pair of tokens. |
.revoke(tokens) | None | Revoke a refresh token. |
.invalidate() | None | Sign the session out. |
.reset() | None | Clear the namespace, database, variables and sign-in of the session. |
.info() | Value | Return the record of the signed-in record user. |
.let(key, value) | None | Define a variable in the session. |
.set(key, value) | None | Another name for .let(). |
.unset(key) | None | Remove a variable from the session. |
.live(table, diff) | LiveSubscription | Start a live query in the session. |
.live_of(live_id) | LiveSubscription | Attach to a live query that was started some other way. |
.subscribe_live(query_uuid) | A generator of notifications | Read the notifications of a live query. |
.kill(query_uuid) | None | Stop a live query. |
.api(path, method, body, headers, query) | ApiResponse | Call an endpoint defined with DEFINE API. |
.gql(query, vars) | list | Run an ISO GQL query. |
.graphql(query, variables, operation_name) | dict | Run a GraphQL query. |
.files | BlockingFiles | A property with helpers for files in storage buckets. |
.timeout(seconds) | A context manager | Change how long requests in the session wait for a reply inside a with block. |
.version() | str | Ask the server for its version. |
The methods that act on the whole connection are not on a session: connect(), close(), health(), subscribe(), new_session(), fork_session(), sessions(), attach(), detach(), export(), export_to() and import_(). Call them on the connection.
Session methods
.begin_transaction()
Begin a transaction in the session. Needs SurrealDB 3.0 or later.
session.begin_transaction()Returns: a BlockingSurrealTransaction, or an AsyncSurrealTransaction on an asynchronous session
The transaction runs with the namespace, database and sign-in of the session. It is a context manager that commits when the block finishes, and cancels when the block raises an exception:
from surrealdb import RecordID
with session.begin_transaction() as txn:
txn.create(RecordID("person", "tobie"), {"name": "Tobie"})
txn.create(RecordID("person", "jaime"), {"name": "Jaime"})On an asynchronous session, write async with await session.begin_transaction() as txn:.
.fork()
Start a new session as a copy of this one. Needs SurrealDB 3.0 or later.
session.fork()Returns: a new session of the same class
The copy gets the namespace, database, variables and access token of the session. It does not get the refresh token, because the server accepts a refresh token only once. The two sessions are independent from then on.
copy = session.fork()
print(copy.query("RETURN session::db()").first())reportsOn an asynchronous session, write copy = await session.fork().
.close_session()
End the session on the server.
session.close_session()Returns: None
The connection and its other sessions stay open. A request on the session object after close_session() raises NotFoundError. Sessions are not context managers, so to end a session also when your code raises an exception, call close_session() in a finally block, as the example below does.
On an asynchronous session, write await session.close_session().
Complete example
The example below runs a transaction in a session that uses another database, and closes the session at the end:
from surrealdb import RecordID, Surreal
with Surreal("ws://localhost:8000") as db:
db.signin({"username": "root", "password": "secret"})
db.use("surrealdb", "docs")
reports = db.new_session()
try:
reports.use("surrealdb", "reports")
with reports.begin_transaction() as txn:
for name in ("Tobie", "Jaime"):
record = RecordID("person", name.lower())
txn.create(record, {"name": name})
query = "SELECT VALUE name FROM person ORDER BY name"
print(reports.query(query).first())
print(db.query("RETURN session::db()").first())
print(reports.id in db.sessions())
finally:
reports.close_session()['Jaime', 'Tobie']
docs
TrueSee also
Multiple sessions for how to use sessions
Surreal for the connection reference with every method in full
SurrealTransaction for the transaction reference
Errors for the error classes