Skip to content

Using synchronous sc.publish ? #52

@Nachimak28

Description

@Nachimak28

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 ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions