37
loading...
This website collects cookies to deliver better user experience
Here for the code alone? Head over to the implementation section of this article.
NOTE: The rest of this article assumes you have a fair understanding of Fauna and Python. Check out my introductory tutorial first if you don't.
NEW DATABASE
button, provide a name for the database, then press SAVE.
We will also be ticking the Pre-populate
option to get demo data that will be used in this article:Security
tab on the Fauna sidebar (located on the left side of the screen), click the NEW KEY
button, provide the necessary information, and press SAVE:
Secret Key.
Copy the key immediately and store it somewhere easily retrievable because it will only be displayed once.pip install faunadb
from faunadb import query as q
from faunadb.objects import Ref
from faunadb.client import FaunaClient
client = FaunaClient(secret="FAUNA_SECRET_KEY")
doc = client.query(
q.get(
q.ref(q.collection("customers"), "101")
)
)
on_start
function, which will be triggered when a document stream starts:def on_start(event):
print(f"started stream at {event.txn}")
data = {
"firstName": "John",
"lastName": "Smith",
"telephone": "719-872-4470"
}
client.query(q.update(doc["ref"], {"data": data}))
on_start
function, we printed out the current timestamp of the transaction emitting the event (in microseconds) provided by event.txn.
Then, the streamed document, so Fauna notifies our application in real-time.on_version
function. It will be triggered when there is a change in the streamed document and Fauna has sent a notification to the subscribing application:def on_version(event):
print(f"on_version event at {event.txn}")
print(f"Event action: {event.event['action']}")
print(f"Changes made: {event.event['diff'].get('data')}")
on_version
function, we printed out the current timestamp again (in microseconds), then printed out the event action provided by event.event['action'].
We then printed out the changes made to the document.on_error
function. It will be triggered when an error occurs while processing the data in the on_version:
def on_error(event):
print(f"Received error event {event}")
on_error
function, we printed out the event that triggered the issue along with its error message.options = {"fields": ["document", "diff", "action"]}
stream = client.stream(doc["ref"], options, on_start, on_error, on_version)
stream.start()
on_start,
on_error,
and on_version
functions to the stream object and triggered it with the start
method. NOTE: You can stop active streams using the stream.close()
method.
data
field.