stan.py icon indicating copy to clipboard operation
stan.py copied to clipboard

Using synchronous sc.publish ?

Open Nachimak28 opened this issue 2 years ago • 0 comments

I am currently working on some microservices and most of the REST APIs are written in flask. Worker services/subscribers using nats and stan and asyncio.

My aim is to have an event published when some API is called and a simple representation of it can be seen in the code below: Note: The code is wrong and is not meant to represent the true working, rather just a representation of an idea, I know that these are based on coroutines and can't be called without encapsulating them in an async function and await them.

from flask import Flask
from nats.aio.client import Client as NATS
from stan.aio.client import Client as STAN
import json

# global NATS and stan connection
nats_connection = NATS()
sc = STAN()
sc.connect(cluster_id='test', client_id='client_id', nats=nats_connection)

def publish_cb(ack):
    print('Message published')

app = Flask(__name__)


@app.route("/")
def index():
    msg = json.dumps({'message': 'hello from the publisher',
                      'data': 'ugradable'}).encode()
    # publish event when this route is called
    sc.publish('test:subject', msg, ack_handler=publish_cb)
    return "Hello World!"

if __name__ == "__main__":

    app.run(host='0.0.0.0', port=8888)

I know that with this library writing such synchronous code is not possible but is there a way to use this library to be used synchronously or maybe I'm looking in the wrong place and there might be an existent synchronous library which can do what the above mentioned code is intended to ?

Nachimak28 avatar Jul 07 '21 16:07 Nachimak28