First, get some events in a DB
Continuing right where we left in the ingest guide, we will use the ORM models to add a few more events.transfer and we will need some values and addresses. We can generate some test data:
Here, we are storing XDR encoded values. We could have instead decided to store decoded values in the database. XDR being a compressed format, choosing when to decode the value is a tradeoff between CPU usage and memory consumption.
Consuming events
Using the same model we used to ingest events into the database, we can query the database to iterate over all events present in the table.Notice previous events being present and having a slightly different formatting. While we are using a schema, it is still easy to corrupt a database. This is only shown for demonstration purposes.
Streaming events
Depending on our application, we might want to consume events periodically by calling the database to see if there is anything new. Or fetch data as needed by our application. There is another possibility: event listeners! While we are at it, we can make the results more readable or usable in Python by using the conversion helper provided by stellar-sdk.Going further
Using the techniques we just presented would probably be enough for a lot of use cases. Still, for the readers wanting to go further there are a few things to look into.Asynchronous programming
So far, we have used SQLAlchemy in a synchronous way. If we were to have an endpoint in the backend calling the database, this endpoint would block during the database call. SQLAlchemy supports asynchronous programming withasync and await keywords.
As a general thought, it’s simpler to start with a synchronous logic and then move on to adding support for async when everything works as expected. Debugging concurrent application brings an additional layer of complexity.
SQLAlchemy allows you to simply change from a synchronous session to an asynchronous one without having to change your models nor queries making it a very easy task to use one or the other.