|
1 | | -# pubsub-python |
| 1 | +# PubSub Python |
| 2 | + |
| 3 | +`pubsub-python` is a Python example illustrating the use of the Syntropy DataMesh project, which facilitates subscription to existing data streams or publishing new ones. This example employs the NATS messaging system and offers a simpler starting point for integrating Python applications with the Syntropy DataMesh platform. |
| 4 | + |
| 5 | +## Example |
| 6 | +Here is a simple example demonstrating how to subscribe to a data stream and republish the received data to another stream: |
| 7 | + |
| 8 | +### The preferred method of authentication is using an access token from the developer portal. |
| 9 | +```python |
| 10 | +import asyncio |
| 11 | +import nats |
| 12 | +import tempfile |
| 13 | +import os |
| 14 | + |
| 15 | +from helper import create_app_jwt |
| 16 | + |
| 17 | +access_token = "SAAGNJOZTRPYYXG2NJX3ZNGXYUSDYX2BWO447W3SHG6XQ7U66RWHQ3JUXM" |
| 18 | + |
| 19 | +async def main(): |
| 20 | + jwt = create_app_jwt(access_token) |
| 21 | + |
| 22 | + # Write the JWT to a temporary file with correct format |
| 23 | + with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as temp: |
| 24 | + temp.write(jwt) |
| 25 | + temp_path = temp.name |
| 26 | + |
| 27 | + nc = await nats.connect("nats://127.0.0.1", user_credentials=temp_path) |
| 28 | + |
| 29 | + async def message_handler(msg): |
| 30 | + subject = msg.subject |
| 31 | + data = msg.data.decode() |
| 32 | + print("Received a message on '{subject}: {data}".format( |
| 33 | + subject=subject, data=data)) |
| 34 | + # await nc.publish("syntropy.test.subject", msg.data) |
| 35 | + |
| 36 | + await nc.subscribe("syntropy.bitcoin.tx", cb=message_handler) |
| 37 | + |
| 38 | + # run infinitely |
| 39 | + while True: |
| 40 | + await asyncio.sleep(1) |
| 41 | + |
| 42 | + # Terminate connection to NATS. |
| 43 | + await nc.drain() |
| 44 | + |
| 45 | + # Delete the temporary file |
| 46 | + os.unlink(temp_path) |
| 47 | + |
| 48 | +if __name__ == '__main__': |
| 49 | + asyncio.run(main()) |
| 50 | +``` |
| 51 | + |
| 52 | +This example demonstrates how to connect to a NATS server, subscribe to a subject, and republish received messages to another subject. |
| 53 | + |
| 54 | +## License |
| 55 | +This project is licensed under the MIT License. |
0 commit comments