Package: nats-py
NATS - Python3 Client for AsyncioAnasyncioPython client for theNATS messaging system.Supported platformsShould be compatible with at leastPython +3.7.Installingpipinstallnats-pyGetting startedimportasyncioimportnatsfromnats.errorsimportConnectionClosedError,TimeoutError,NoServersErrorasyncdefmain():# It is very likely that the demo server will see traffic from clients other than yours.# To avoid this, start your own locally and modify the example to use it.nc=awaitnats.connect("nats://demo.nats.io:4222")# You can also use the following for TLS against the demo server.## nc = await nats.connect("tls://demo.nats.io:4443")asyncdefmessage_handler(msg):subject=msg.subjectreply=msg.replydata=msg.data.decode()print("Received a message on '{subject}{reply}':{data}".format(subject=subject,reply=reply,data=data))# Simple publisher and async subscriber via coroutine.sub=awaitnc.subscribe("foo",cb=message_handler)# Stop receiving after 2 messages.awaitsub.unsubscribe(limit=2)awaitnc.publish("foo",b'Hello')awaitnc.publish("foo",b'World')awaitnc.publish("foo",b'!!!!!')# Synchronous style with iterator also supported.sub=awaitnc.subscribe("bar")awaitnc.publish("bar",b'First')awaitnc.publish("bar",b'Second')try:asyncformsginsub.messages:print(f"Received a message on '{msg.subject}{msg.reply}':{msg.data.decode()}")awaitsub.unsubscribe()exceptExceptionase:passasyncdefhelp_request(msg):print(f"Received a message on '{msg.subject}{msg.reply}':{msg.data.decode()}")awaitnc.publish(msg.reply,b'I can help')# Use queue named 'workers' for distributing requests# among subscribers.sub=awaitnc.subscribe("help","workers",help_request)# Send a request and expect a single response# and trigger timeout if not faster than 500 ms.try:response=awaitnc.request("help",b'help me',timeout=0.5)print("Received response:{message}".format(message=response.data.decode()))exceptTimeoutError:print("Request timed out")# Remove interest in subscription.awaitsub.unsubscribe()# Terminate connection to NATS.awaitnc.drain()if__name__=='__main__':asyncio.run(main())JetStreamStarting v2.0.0 series, the client now has JetStream support:importasyncioimportnatsfromnats.errorsimportTimeoutErrorasyncdefmain():nc=awaitnats.connect("localhost")# Create JetStream context.js=nc.jetstream()# Persist messages on 'foo's subject.awaitjs.add_stream(name="sample-stream",subjects=["foo"])foriinrange(0,10):ack=awaitjs.publish("foo",f"hello world:{i}".encode())print(ack)# Create pull based consumer on 'foo'.psub=awaitjs.pull_subscribe("foo","psub")# Fetch and ack messagess from consumer.foriinrange(0,10):msgs=awaitpsub.fetch(1)formsginmsgs:awaitmsg.ack()print(msg)# Create single ephemeral push based subscriber.sub=awaitjs.subscribe("foo")msg=awaitsub.next_msg()awaitmsg.ack()# Create single push based subscriber that is durable across restarts.sub=awaitjs.subscribe("foo",durable="myapp")msg=awaitsub.next_msg()awaitmsg.ack()# Create deliver group that will be have load balanced messages.asyncdefqsub_a(msg):print("QSUB A:",msg)awaitmsg.ack()asyncdefqsub_b(msg):print("QSUB B:",msg)awaitmsg.ack()awaitjs.subscribe("foo","workers",cb=qsub_a)awaitjs.subscribe("foo","workers",cb=qsub_b)foriinrange(0,10):ack=awaitjs.publish("foo",f"hello world:{i}".encode())print("\t",ack)# Create ordered consumer with flow control and heartbeats# that auto resumes on failures.osub=awaitjs.subscribe("foo",ordered_consumer=True)data=bytearray()whileTrue:try:msg=awaitosub.next_msg()data.extend(msg.data)exceptTimeoutError:breakprint("All data in stream:",len(data))awaitnc.close()if__name__=='__main__':asyncio.run(main())TLSTLS connections can be configured with anssl contextssl_ctx=ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)ssl_ctx.load_verify_locations('ca.pem')ssl_ctx.load_cert_chain(certfile='client-cert.pem',keyfile='client-key.pem')awaitnats.connect(servers=["tls://127.0.0.1:4443"],tls=ssl_ctx,tls_hostname="localhost")Setting the scheme totlsin the connect URL will make the client create adefault ssl contextautomatically:importasyncioimportsslfromnats.aio.clientimportClientasNATSasyncdefrun():nc=NATS()awaitnc.connect("tls://demo.nats.io:4443")Note: If getting SSL certificate errors in OS X, try first installing thecertificertificate bundle. If using Python 3.7 for example, then run:$ /Applications/Python\ 3.7/Install\ Certificates.command
 -- pip install --upgrade certifi
Collecting certifi
...
 -- removing any existing file or link
 -- creating symlink to certifi certificate bundle
 -- setting permissions
 -- update completeNKEYS and JWT User CredentialsSincev0.9.0release,
you can also optionally installNKEYSin order to use
the new NATS v2.0 auth features:pipinstallnats-py[nkeys]Usage:awaitnats.connect("tls://connect.ngs.global:4222",user_credentials="/path/to/secret.creds")DevelopmentInstall nats server.Make sure the server is available in your PATH:nats-server -v.Install dependencies:python3 -m pipenv install --dev.Run tests:python3 -m pytest.LicenseUnless otherwise noted, the NATS source files are distributed under
the Apache Version 2.0 license found in the LICENSE file.