Skip to content

Realtime Database reference

At a glance

  • Database.database(url=None): reference(path), reference_from_url(url), use_emulator(host, port), persistence_enabled, persistence_cache_size_bytes, go_offline(), go_online(), purge_outstanding_writes(), set_logging_enabled(enabled), sdk_version()
  • DatabaseQuery: order_by_child(path), order_by_key(), order_by_value(), order_by_priority(), start_at(value, child_key), start_after, end_at, end_before, equal_to, limit_to_first(n), limit_to_last(n); observe(event_type, callback, cancel_callback) → DatabaseObserver (remove()), observe_once(...), get_data(cb), remove_all_observers(), keep_synced(bool), ref
  • DatabaseReference(DatabaseQuery): key, url, path, parent, root, database, child(path), child_by_auto_id(); set_value(value, cb, *, priority), update_child_values(values, cb), remove_value(cb), set_priority(priority, cb), run_transaction(update, cb, *, local_events), on_disconnect() → OnDisconnect (set_value, update_child_values, remove_value, cancel)
  • DataSnapshot: key, value, priority, export_value(), exists(), child(path), has_child(path), has_children(), children_count, iteration over the children, ref
  • MutableData: key, value (settable), priority (settable), child(path), has_child, has_children, children_count, children; TransactionResult.success(data), TransactionResult.abort()
  • ServerValue.timestamp(), ServerValue.increment(delta), to_database(value); DataEventType; DatabaseError (name), DatabaseErrorCode, DATABASE_ERROR_DOMAIN, TRANSACTION_ERROR_DOMAIN

pyios_firebase.database

Firebase Realtime Database: a JSON tree, synced live to every client.

from pyios_firebase.database import DataEventType, Database, ServerValue

db = Database.database()
messages = db.reference("rooms/general/messages")

messages.child_by_auto_id().set_value(
    {"text": "Hello", "sent_at": ServerValue.timestamp()}
)

def on_message(snapshot, previous_key):
    print(snapshot.key, snapshot.value)

observer = messages.order_by_child("sent_at").limit_to_last(50).observe(
    DataEventType.CHILD_ADDED, on_message
)
...
observer.remove()

Values are Python values: dict, list, str, int, float, bool and None. Bad paths, keys, values and queries raise ValueError or TypeError (the SDK would raise an Objective-C exception, which aborts the app).

Needs the FirebaseDatabase framework.

Modules:

Name Description
database

Database: the entry point of the Realtime Database.

errors

Realtime Database errors.

query

DatabaseQuery: sorting, filtering and listening to data.

reference

DatabaseReference: a location in the database, and writes to it.

snapshot

DataSnapshot (data read from the database) and MutableData (data in

values

Python values and paths for the Realtime Database.

Classes:

Name Description
Database

A Realtime Database. Get it with Database.database().

DatabaseError

An error from the Realtime Database.

DatabaseErrorCode

The error.code values of database errors (DATABASE_ERROR_DOMAIN).

DataEventType

What to listen to (FIRDataEventType).

DatabaseObserver

Given back by observe. Call remove() to stop listening.

DatabaseQuery

A sorted and filtered view of the data at a location. Every method that

DatabaseReference

A location in the database. Read and listen with the query methods, and

OnDisconnect

Writes the server makes when this client disconnects (closes the app,

TransactionResult

What a transaction function returns: success (write the data) or

DataSnapshot

The data at a location, at the time it was read. It does not change.

MutableData

The current data at a location, inside a transaction. Change value

ServerValue

Values the server fills in when it applies the write.

Functions:

Name Description
to_database

Turn a Python value into what the database SDK writes.

Attributes:

Name Type Description
DATABASE_ERROR_DOMAIN Final

The error.domain of errors from the database server.

EventCallback

(snapshot, previous_child_key). For child events, previous_child_key

TRANSACTION_ERROR_DOMAIN Final

The error.domain when the Python transaction function raised.

TransactionCallback

(error, committed, snapshot). committed is False when the

WriteCallback

(error): None once the server has the write, or the error.

DATABASE_ERROR_DOMAIN module-attribute

DATABASE_ERROR_DOMAIN: Final = 'com.firebase'

The error.domain of errors from the database server.

EventCallback module-attribute

EventCallback = Callable[[DataSnapshot, "str | None"], None]

(snapshot, previous_child_key). For child events, previous_child_key is the key of the child before this one in the query's order (None for the first); for VALUE it is None.

TRANSACTION_ERROR_DOMAIN module-attribute

TRANSACTION_ERROR_DOMAIN: Final = (
    "pyios_firebase.database.transaction"
)

The error.domain when the Python transaction function raised.

TransactionCallback module-attribute

TransactionCallback = Callable[
    [DatabaseError | None, bool, DataSnapshot | None], None
]

(error, committed, snapshot). committed is False when the transaction was aborted (or failed); snapshot is the data after it.

WriteCallback module-attribute

WriteCallback = Callable[[DatabaseError | None], None]

(error): None once the server has the write, or the error.

Database

Database(native: ObjCObject)

A Realtime Database. Get it with Database.database().

Parameters:

Name Type Description Default
native ObjCObject

the native FIRDatabase.

required

Methods:

Name Description
database

The shared Database of the default Firebase app.

reference

A location in the database.

reference_from_url

A location, from its full URL.

use_emulator

Use the local Realtime Database emulator. Call it before any other

go_offline

Disconnect from the server. Reads come from the cache and writes

go_online

Reconnect after go_offline.

purge_outstanding_writes

Drop the writes not yet sent to the server (their callbacks get

set_logging_enabled

Log the SDK's debug messages to the console.

sdk_version

The Firebase Database SDK version.

Attributes:

Name Type Description
native ObjCObject

The FIRDatabase.

persistence_enabled bool

Keep the data and the pending writes on disk, so they survive app

persistence_cache_size_bytes int

The most disk the cache may use (1 MB to 100 MB; default 10 MB). Set

native property

native: ObjCObject

The FIRDatabase.

persistence_enabled property writable

persistence_enabled: bool

Keep the data and the pending writes on disk, so they survive app restarts (off by default). Set it before any other use of this database.

persistence_cache_size_bytes property writable

persistence_cache_size_bytes: int

The most disk the cache may use (1 MB to 100 MB; default 10 MB). Set it before any other use of this database.

database classmethod

database(url: str | None = None) -> Database

The shared Database of the default Firebase app.

Parameters:

Name Type Description Default
url str | None

the database URL, for example "https://my-db.europe-west1.firebasedatabase.app". None means the app's default database (DATABASE_URL in GoogleService-Info.plist).

None

Returns:

Type Description
Database

The same Database for the same URL.

reference

reference(path: str | None = None) -> DatabaseReference

A location in the database.

Parameters:

Name Type Description Default
path str | None

the path from the root, for example "users/ada". None or "" means the root. ".info/connected" is True while the client is connected.

None

Returns:

Type Description
DatabaseReference

A DatabaseReference.

Raises:

Type Description
ValueError

the path holds . # $ [ ].

reference_from_url

reference_from_url(url: str) -> DatabaseReference

A location, from its full URL.

Parameters:

Name Type Description Default
url str

for example "https://my-db.firebaseio.com/users/ada". It must be in this database.

required

Returns:

Type Description
DatabaseReference

A DatabaseReference.

use_emulator

use_emulator(
    host: str = "127.0.0.1", port: int = 9000
) -> None

Use the local Realtime Database emulator. Call it before any other use of this database; use it only in development and test builds.

Parameters:

Name Type Description Default
host str

the emulator's host. "127.0.0.1" works in the iOS Simulator; on a device, use the Mac's LAN address.

'127.0.0.1'
port int

the emulator's port (firebase emulators:start uses 9000).

9000

go_offline

go_offline() -> None

Disconnect from the server. Reads come from the cache and writes are queued until go_online.

go_online

go_online() -> None

Reconnect after go_offline.

purge_outstanding_writes

purge_outstanding_writes() -> None

Drop the writes not yet sent to the server (their callbacks get WRITE_CANCELED). Useful after a long time offline.

set_logging_enabled staticmethod

set_logging_enabled(enabled: bool) -> None

Log the SDK's debug messages to the console.

Parameters:

Name Type Description Default
enabled bool

True to log.

required

sdk_version staticmethod

sdk_version() -> str

The Firebase Database SDK version.

DatabaseError

Bases: FirebaseError

An error from the Realtime Database.

Attributes:

Name Type Description
name str

The DatabaseErrorCode name of code (for example

name instance-attribute

name: str

The DatabaseErrorCode name of code (for example "PERMISSION_DENIED"), or "" for errors from other domains (such as get_data failing offline).

DatabaseErrorCode

The error.code values of database errors (DATABASE_ERROR_DOMAIN).

Attributes:

Name Type Description
PERMISSION_DENIED Final

The security rules do not allow this read or write.

UNAVAILABLE Final

The server is unavailable.

WRITE_CANCELED Final

The write was cancelled (for example by purge_outstanding_writes).

OTHER Final

Any other server status. description has the status (for example

PERMISSION_DENIED class-attribute instance-attribute

PERMISSION_DENIED: Final = 1

The security rules do not allow this read or write.

UNAVAILABLE class-attribute instance-attribute

UNAVAILABLE: Final = 2

The server is unavailable.

WRITE_CANCELED class-attribute instance-attribute

WRITE_CANCELED: Final = 3

The write was cancelled (for example by purge_outstanding_writes).

OTHER class-attribute instance-attribute

OTHER: Final = 9999

Any other server status. description has the status (for example "datastale" or "maxretry" for a transaction).

DataEventType

What to listen to (FIRDataEventType).

Attributes:

Name Type Description
CHILD_ADDED Final

A child was added (and once for each existing child, at the start).

CHILD_REMOVED Final

A child was removed.

CHILD_CHANGED Final

A child (or anything below it) changed.

CHILD_MOVED Final

A child moved in the query's order.

VALUE Final

The data at the location (or anything below it) changed. Called once

CHILD_ADDED class-attribute instance-attribute

CHILD_ADDED: Final = 0

A child was added (and once for each existing child, at the start).

CHILD_REMOVED class-attribute instance-attribute

CHILD_REMOVED: Final = 1

A child was removed.

CHILD_CHANGED class-attribute instance-attribute

CHILD_CHANGED: Final = 2

A child (or anything below it) changed.

CHILD_MOVED class-attribute instance-attribute

CHILD_MOVED: Final = 3

A child moved in the query's order.

VALUE class-attribute instance-attribute

VALUE: Final = 4

The data at the location (or anything below it) changed. Called once with the current data at the start.

DatabaseObserver

DatabaseObserver(
    query: ObjCObject,
    handle: int,
    release: Callable[[], None],
)

Given back by observe. Call remove() to stop listening.

Parameters:

Name Type Description Default
query ObjCObject

the native query the observer was added to.

required
handle int

the SDK's handle for the observer.

required
release Callable[[], None]

releases the observer's blocks.

required

Methods:

Name Description
remove

Stop the updates. Safe to call more than once.

Attributes:

Name Type Description
handle int

The SDK's FIRDatabaseHandle.

handle property

handle: int

The SDK's FIRDatabaseHandle.

remove

remove() -> None

Stop the updates. Safe to call more than once.

DatabaseQuery

DatabaseQuery(
    native: ObjCObject, _spec: _Spec | None = None
)

A sorted and filtered view of the data at a location. Every method that narrows the query returns a new query; nothing is read until you observe or get_data.

::

top = ref.child("scores").order_by_value().limit_to_last(10)
observer = top.observe(DataEventType.CHILD_ADDED, on_score)

Each query can be ordered once, and have one start, one end and one limit.

Parameters:

Name Type Description Default
native ObjCObject

the native FIRDatabaseQuery (or FIRDatabaseReference).

required

Methods:

Name Description
order_by_child

Sort by the value of a child of each child.

order_by_key

Sort by the children's keys.

order_by_value

Sort by the children's values.

order_by_priority

Sort by the children's priorities.

start_at

Only children at or after value in the query's order.

start_after

Only children after value (excluded) in the query's order.

end_at

Only children at or before value in the query's order.

end_before

Only children before value (excluded) in the query's order.

equal_to

Only children equal to value in the query's order.

limit_to_first

Only the first limit children in the query's order.

limit_to_last

Only the last limit children in the query's order.

observe

Listen to changes. callback runs on the main thread, at the start

observe_once

Get the next event once (for VALUE: the data now, from the cache

get_data

Read the data from the server (or from the cache when offline and

remove_all_observers

Remove every observer of this query (and, on a reference, of the

keep_synced

Keep this query's data in the cache and up to date, even without

Attributes:

Name Type Description
native ObjCObject

The FIRDatabaseQuery.

ref DatabaseReference

The location this query reads from.

native property

native: ObjCObject

The FIRDatabaseQuery.

ref property

The location this query reads from.

order_by_child

order_by_child(path: str) -> DatabaseQuery

Sort by the value of a child of each child.

Parameters:

Name Type Description Default
path str

the child's path in each child, for example "age" or "stats/score".

required

Returns:

Type Description
DatabaseQuery

The new query.

Raises:

Type Description
ValueError

the query is already ordered, or path is invalid ("$key" / "$value" / "$priority": use order_by_key / order_by_value / order_by_priority).

order_by_key

order_by_key() -> DatabaseQuery

Sort by the children's keys.

Raises:

Type Description
ValueError

the query is already ordered, or has a non-str start or end value or a child key.

TypeError

a start or end value is not a str.

order_by_value

order_by_value() -> DatabaseQuery

Sort by the children's values.

Raises:

Type Description
ValueError

the query is already ordered.

order_by_priority

order_by_priority() -> DatabaseQuery

Sort by the children's priorities.

Raises:

Type Description
ValueError

the query is already ordered.

TypeError

a start or end value is a bool.

start_at

start_at(
    value: Any, child_key: str | None = None
) -> DatabaseQuery

Only children at or after value in the query's order.

Parameters:

Name Type Description Default
value Any

None, bool, a number or a str (a str key with order_by_key).

required
child_key str | None

among children with exactly value, start at this key. Not with order_by_key.

None

Returns:

Type Description
DatabaseQuery

The new query.

Raises:

Type Description
ValueError

the query already has a start, or a bad child_key.

TypeError

a value type the query cannot use.

start_after

start_after(
    value: Any, child_key: str | None = None
) -> DatabaseQuery

Only children after value (excluded) in the query's order.

Parameters:

Name Type Description Default
value Any

as for start_at.

required
child_key str | None

among children with exactly value, start after this key.

None

Returns:

Type Description
DatabaseQuery

The new query.

Raises:

Type Description
ValueError

the query already has a start, or a bad child_key.

TypeError

a value type the query cannot use.

end_at

end_at(
    value: Any, child_key: str | None = None
) -> DatabaseQuery

Only children at or before value in the query's order.

Parameters:

Name Type Description Default
value Any

as for start_at.

required
child_key str | None

among children with exactly value, end at this key.

None

Returns:

Type Description
DatabaseQuery

The new query.

Raises:

Type Description
ValueError

the query already has an end, or a bad child_key.

TypeError

a value type the query cannot use.

end_before

end_before(
    value: Any, child_key: str | None = None
) -> DatabaseQuery

Only children before value (excluded) in the query's order.

Parameters:

Name Type Description Default
value Any

as for start_at.

required
child_key str | None

among children with exactly value, end before this key.

None

Returns:

Type Description
DatabaseQuery

The new query.

Raises:

Type Description
ValueError

the query already has an end, or a bad child_key.

TypeError

a value type the query cannot use.

equal_to

equal_to(
    value: Any, child_key: str | None = None
) -> DatabaseQuery

Only children equal to value in the query's order.

Parameters:

Name Type Description Default
value Any

as for start_at.

required
child_key str | None

only the child with this key (among those equal to value).

None

Returns:

Type Description
DatabaseQuery

The new query.

Raises:

Type Description
ValueError

the query already has a start or an end, or a bad child_key.

TypeError

a value type the query cannot use.

limit_to_first

limit_to_first(limit: int) -> DatabaseQuery

Only the first limit children in the query's order.

Parameters:

Name Type Description Default
limit int

how many (1 to 2,147,483,647).

required

Returns:

Type Description
DatabaseQuery

The new query.

Raises:

Type Description
ValueError

the query already has a limit, or limit is out of range.

limit_to_last

limit_to_last(limit: int) -> DatabaseQuery

Only the last limit children in the query's order.

Parameters:

Name Type Description Default
limit int

how many (1 to 2,147,483,647).

required

Returns:

Type Description
DatabaseQuery

The new query.

Raises:

Type Description
ValueError

the query already has a limit, or limit is out of range.

observe

observe(
    event_type: int,
    callback: EventCallback,
    cancel_callback: CancelCallback | None = None,
) -> DatabaseObserver

Listen to changes. callback runs on the main thread, at the start and on every change, until you remove() the observer.

Parameters:

Name Type Description Default
event_type int

a DataEventType.

required
callback EventCallback

gets (snapshot, previous_child_key).

required
cancel_callback CancelCallback | None

gets a DatabaseError if the server stops the listener (for example PERMISSION_DENIED). The observer is then already removed.

None

Returns:

Type Description
DatabaseObserver

A DatabaseObserver.

Raises:

Type Description
ValueError

an unknown event_type.

observe_once

observe_once(
    event_type: int,
    callback: EventCallback,
    cancel_callback: CancelCallback | None = None,
) -> None

Get the next event once (for VALUE: the data now, from the cache if the SDK has it).

Prefer get_data to read fresh data from the server.

Parameters:

Name Type Description Default
event_type int

a DataEventType.

required
callback EventCallback

gets (snapshot, previous_child_key), once.

required
cancel_callback CancelCallback | None

gets a DatabaseError instead, if the read is not allowed.

None

Raises:

Type Description
ValueError

an unknown event_type.

get_data

get_data(
    callback: Callable[
        [DataSnapshot | None, DatabaseError | None], None
    ],
) -> None

Read the data from the server (or from the cache when offline and the SDK has it).

Parameters:

Name Type Description Default
callback Callable[[DataSnapshot | None, DatabaseError | None], None]

gets (snapshot, None), or (None, error) (for example when offline with nothing cached).

required

remove_all_observers

remove_all_observers() -> None

Remove every observer of this query (and, on a reference, of the location without filters). Observers of child locations stay.

keep_synced

keep_synced(keep_synced: bool) -> None

Keep this query's data in the cache and up to date, even without observers (useful with persistence, for offline use).

Parameters:

Name Type Description Default
keep_synced bool

True to start, False to stop.

required

Raises:

Type Description
ValueError

the query is on .info.

DatabaseReference

DatabaseReference(
    native: ObjCObject, _spec: _Spec | None = None
)

Bases: DatabaseQuery

A location in the database. Read and listen with the query methods, and write with set_value, update_child_values... Nothing happens until you call a method.

Writes show in local listeners at once, and work offline: the SDK sends them when it is back online. The callbacks run when the server has them.

Parameters:

Name Type Description Default
native ObjCObject

the native FIRDatabaseReference.

required

Methods:

Name Description
child

A location below this one.

child_by_auto_id

A new child with a unique key that sorts by creation time (like

on_disconnect

Writes to make at this location when this client disconnects.

set_value

Replace the data at this location (and everything below it).

update_child_values

Write some children, leaving the others. Keys can be paths, to write

remove_value

Delete the data at this location (and everything below it).

set_priority

Set the priority of the data here (used by order_by_priority).

run_transaction

Change the data atomically, from its current value::

Attributes:

Name Type Description
key str | None

The last part of the path (None for the root).

url str

The full URL of the location.

path str

The path from the root, for example "/users/ada" ("/" for

database Database

The Database this reference belongs to.

parent DatabaseReference | None

The location above this one, or None at the root.

root DatabaseReference

The root of the database.

key property

key: str | None

The last part of the path (None for the root).

url property

url: str

The full URL of the location.

path property

path: str

The path from the root, for example "/users/ada" ("/" for the root).

database property

database: Database

The Database this reference belongs to.

parent property

parent: DatabaseReference | None

The location above this one, or None at the root.

root property

The root of the database.

child

child(path: str) -> DatabaseReference

A location below this one.

Parameters:

Name Type Description Default
path str

a relative path, for example "ada" or "ada/scores".

required

Returns:

Type Description
DatabaseReference

A new DatabaseReference.

Raises:

Type Description
ValueError

the path is empty or holds . # $ [ ].

child_by_auto_id

child_by_auto_id() -> DatabaseReference

A new child with a unique key that sorts by creation time (like push() in other SDKs). Nothing is written until you write to it.

on_disconnect

on_disconnect() -> OnDisconnect

Writes to make at this location when this client disconnects.

set_value

set_value(
    value: Any,
    callback: WriteCallback | None = None,
    *,
    priority: Any = None,
) -> None

Replace the data at this location (and everything below it).

Parameters:

Name Type Description Default
value Any

None (delete), bool, int, float, str, a ServerValue, or a dict (str keys), list or tuple of those.

required
callback WriteCallback | None

gets (error) once the server has the write.

None
priority Any

also set this priority (a number or str).

None

Raises:

Type Description
TypeError

a value the database cannot store (datetime, bytes...).

ValueError

an invalid key or value, or a location under .info.

update_child_values

update_child_values(
    values: Mapping[str, Any],
    callback: WriteCallback | None = None,
) -> None

Write some children, leaving the others. Keys can be paths, to write to several locations at once (atomically)::

root.update_child_values({
    f"posts/{key}": post,
    f"user-posts/{uid}/{key}": post,
})

Parameters:

Name Type Description Default
values Mapping[str, Any]

paths (relative to here) to values. None deletes.

required
callback WriteCallback | None

gets (error) once the server has the write.

None

Raises:

Type Description
TypeError

a value the database cannot store.

ValueError

an invalid path or value, a path at or below another one, or a location under .info.

remove_value

remove_value(callback: WriteCallback | None = None) -> None

Delete the data at this location (and everything below it).

Parameters:

Name Type Description Default
callback WriteCallback | None

gets (error) once the server has the delete.

None

Raises:

Type Description
ValueError

a location under .info.

set_priority

set_priority(
    priority: str | float | None,
    callback: WriteCallback | None = None,
) -> None

Set the priority of the data here (used by order_by_priority).

Parameters:

Name Type Description Default
priority str | float | None

a number, a str, or None to remove it.

required
callback WriteCallback | None

gets (error) once the server has the write.

None

Raises:

Type Description
TypeError

another type (bool too).

ValueError

a location under .info.

run_transaction

run_transaction(
    update: Callable[[MutableData], TransactionResult],
    callback: TransactionCallback | None = None,
    *,
    local_events: bool = True,
) -> None

Change the data atomically, from its current value::

def add_like(data):
    data.value = (data.value or 0) + 1
    return TransactionResult.success(data)

ref.child("likes").run_transaction(add_like)

update may run several times (on a background thread): whenever another client changed the data first, it runs again with the new data. It must not have side effects.

Parameters:

Name Type Description Default
update Callable[[MutableData], TransactionResult]

gets the current MutableData and returns TransactionResult.success(data) or TransactionResult.abort(). If it raises, the transaction is aborted and callback gets the error.

required
callback TransactionCallback | None

gets (error, committed, snapshot) at the end.

None
local_events bool

show the intermediate values in local listeners. False shows only the committed value.

True

Raises:

Type Description
ValueError

a location under .info.

OnDisconnect

OnDisconnect(ref: ObjCObject)

Writes the server makes when this client disconnects (closes the app, loses the network...). Get it with ref.on_disconnect().

The writes are queued on the server now, and run even if the app is killed. The callbacks say when the server has queued them.

Parameters:

Name Type Description Default
ref ObjCObject

the native FIRDatabaseReference.

required

Methods:

Name Description
set_value

Write value on disconnect.

update_child_values

Update children on disconnect.

remove_value

Delete the data on disconnect.

cancel

Cancel the disconnect writes queued at this location (and below).

set_value

set_value(
    value: Any,
    callback: WriteCallback | None = None,
    *,
    priority: Any = None,
) -> None

Write value on disconnect.

Parameters:

Name Type Description Default
value Any

as for DatabaseReference.set_value.

required
callback WriteCallback | None

gets (error) once the server has queued the write.

None
priority Any

also set this priority (None: leave it).

None

update_child_values

update_child_values(
    values: Mapping[str, Any],
    callback: WriteCallback | None = None,
) -> None

Update children on disconnect.

Parameters:

Name Type Description Default
values Mapping[str, Any]

as for DatabaseReference.update_child_values.

required
callback WriteCallback | None

gets (error) once the server has queued the write.

None

remove_value

remove_value(callback: WriteCallback | None = None) -> None

Delete the data on disconnect.

Parameters:

Name Type Description Default
callback WriteCallback | None

gets (error) once the server has queued the delete.

None

cancel

cancel(callback: WriteCallback | None = None) -> None

Cancel the disconnect writes queued at this location (and below).

Parameters:

Name Type Description Default
callback WriteCallback | None

gets (error) once the server has cancelled them.

None

TransactionResult

TransactionResult(native: ObjCObject)

What a transaction function returns: success (write the data) or abort (write nothing).

Parameters:

Name Type Description Default
native ObjCObject

the native FIRTransactionResult.

required

Methods:

Name Description
success

Write data (the MutableData the function got, changed).

abort

Write nothing. The callback gets committed=False.

Attributes:

Name Type Description
native ObjCObject

The FIRTransactionResult.

native property

native: ObjCObject

The FIRTransactionResult.

success classmethod

success(data: MutableData) -> TransactionResult

Write data (the MutableData the function got, changed).

Parameters:

Name Type Description Default
data MutableData

the new data.

required

abort classmethod

abort() -> TransactionResult

Write nothing. The callback gets committed=False.

DataSnapshot

DataSnapshot(native: ObjCObject)

The data at a location, at the time it was read. It does not change.

value is the data as Python values. Iterating a snapshot gives its children, in the query's order::

for child in snapshot:
    print(child.key, child.value)

Parameters:

Name Type Description Default
native ObjCObject

the native FIRDataSnapshot.

required

Methods:

Name Description
export_value

The data with priorities included (".value" / ".priority"

exists

True if there is data (value is not None).

child

The data at a path below this one (an empty snapshot if none).

has_child

True if there is data at a path below this one.

has_children

True if the data has children (it is an object, not a leaf).

Attributes:

Name Type Description
native ObjCObject

The FIRDataSnapshot.

key str | None

The last part of the location's path (None for the root).

value Any

The data, as Python values: dict, list, str, int,

priority str | float | None

The priority of the data, or None.

ref DatabaseReference

The location this data was read from.

children_count int

How many children the data has.

native property

native: ObjCObject

The FIRDataSnapshot.

key property

key: str | None

The last part of the location's path (None for the root).

value property

value: Any

The data, as Python values: dict, list, str, int, float, bool, or None when there is no data.

Objects whose keys are "0", "1"... (mostly) come back as a list, as the SDK reads them.

priority property

priority: str | float | None

The priority of the data, or None.

ref property

The location this data was read from.

children_count property

children_count: int

How many children the data has.

export_value

export_value() -> Any

The data with priorities included (".value" / ".priority" keys), as Python values. Write it back with set_value to copy the data with its priorities.

exists

exists() -> bool

True if there is data (value is not None).

child

child(path: str) -> DataSnapshot

The data at a path below this one (an empty snapshot if none).

Parameters:

Name Type Description Default
path str

a relative path, for example "name" or "address/city".

required

Raises:

Type Description
ValueError

an invalid path.

has_child

has_child(path: str) -> bool

True if there is data at a path below this one.

Parameters:

Name Type Description Default
path str

a relative path.

required

Raises:

Type Description
ValueError

an invalid path.

has_children

has_children() -> bool

True if the data has children (it is an object, not a leaf).

MutableData

MutableData(native: ObjCObject)

The current data at a location, inside a transaction. Change value (or a child's) and return TransactionResult.success(data).

Parameters:

Name Type Description Default
native ObjCObject

the native FIRMutableData.

required

Methods:

Name Description
child

The data at a path below this one. Changing it changes this data.

has_child

True if there is data at a path below this one.

has_children

True if the data has children.

Attributes:

Name Type Description
native ObjCObject

The FIRMutableData.

key str | None

The last part of the location's path.

value Any

The data, as Python values (None when there is none). Setting it

priority str | float | None

The priority (None, a number or a str). Settable.

children_count int

How many children the data has.

children list[MutableData]

The children, each as MutableData.

native property

native: ObjCObject

The FIRMutableData.

key property

key: str | None

The last part of the location's path.

value property writable

value: Any

The data, as Python values (None when there is none). Setting it replaces the data; None deletes it.

The first time a transaction runs, this may be None while the server has data: the SDK has nothing cached yet. Return a value anyway; the SDK runs the transaction again with the server's data.

priority property writable

priority: str | float | None

The priority (None, a number or a str). Settable.

children_count property

children_count: int

How many children the data has.

children property

children: list[MutableData]

The children, each as MutableData.

child

child(path: str) -> MutableData

The data at a path below this one. Changing it changes this data.

Parameters:

Name Type Description Default
path str

a relative path.

required

Raises:

Type Description
ValueError

an invalid path.

has_child

has_child(path: str) -> bool

True if there is data at a path below this one.

Parameters:

Name Type Description Default
path str

a relative path.

required

Raises:

Type Description
ValueError

an invalid path.

has_children

has_children() -> bool

True if the data has children.

ServerValue

Values the server fills in when it applies the write.

::

ref.set_value({"text": "hi", "sent_at": ServerValue.timestamp()})
ref.child("likes").set_value(ServerValue.increment(1))

Methods:

Name Description
timestamp

The server's time, in milliseconds since 1970, when it writes the value.

increment

Add delta to the number stored on the server (atomically; a

timestamp staticmethod

timestamp() -> dict[str, Any]

The server's time, in milliseconds since 1970, when it writes the value.

Returns:

Type Description
dict[str, Any]

The placeholder to write ({".sv": "timestamp"}).

increment staticmethod

increment(delta: float) -> dict[str, Any]

Add delta to the number stored on the server (atomically; a missing or non-number value counts as 0).

Parameters:

Name Type Description Default
delta float

the amount to add (negative to subtract).

required

Returns:

Type Description
dict[str, Any]

The placeholder to write ({".sv": {"increment": delta}}).

Raises:

Type Description
TypeError

delta is not an int or float (or is a bool).

ValueError

delta is nan or infinite.

to_database

to_database(value: Any) -> Any

Turn a Python value into what the database SDK writes.

Parameters:

Name Type Description Default
value Any

None, bool, int, float, str, a ServerValue placeholder, or a dict (str keys), list or tuple of those. None deletes the value. Lists are stored as objects with keys "0", "1"...

required

Returns:

Type Description
Any

The Objective-C value.

Raises:

Type Description
TypeError

a value the database cannot store (datetime, bytes, set...) or a key that is not a str. The message names the path of the bad value.

ValueError

an invalid key, nan / inf, or a string over 10 MB.