Replies: 4 comments
-
AFAIK, Try async def init() -> nats.NATS:
nc = await nats.connect("nats://localhost:4222")
return nc
async def publish(nc: nats.NATS):
st = bytes("str", "utf-8")
await nc.publish("subj", st)
async def not_working():
nc = await init()
await publish(nc)
await nc.drain()
if __name__ == "__main__":
asyncio.run(not_working()) |
Beta Was this translation helpful? Give feedback.
-
something like the following would work: import asyncio
import nats
async def main():
nc = await nats.connect("tls://demo.nats.io:4443")
await nc.publish("test", b'hello')
await nc.close() # so that buffer is flushed and sent
if __name__ == '__main__':
asyncio.run(main()) |
Beta Was this translation helpful? Give feedback.
-
Thanks, but actually i was trying to initialise nats connection in the init function and reuse the created connection while publishing, however i cant use await in init, from the various examples i saw, its like we have to initialize the connection each time before publishing a new message, i am not sure if that's the right approach How can i reuse the connection after initialising it once |
Beta Was this translation helpful? Give feedback.
-
Added an example of wrapping a class for the connection to reuse it later here: https://github.com/nats-io/nats.py/blob/main/examples/component.py |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
As per the code block, when i am initialising the nats and publishing in diff function the message isnt received on consumer, however it works when i init and publish in one function
EDIT:Actually i was trying to initialise nats connection in the init function and reuse the created connection while publishing, however i cant use await in init, from the various examples i saw, its like we have to initialize the connection each time before publishing a new message, i am not sure if that's the right approach
Beta Was this translation helpful? Give feedback.
All reactions