-
Notifications
You must be signed in to change notification settings - Fork 195
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
django and nats #330
Comments
Here's a simplified example of how you might structure your code using Django Channels:
import asyncio
from nats.aio import connect, errors
class NatsClient:
def __init__(self, token, servers):
self.token = token
self.servers = servers
self.loop = asyncio.get_event_loop()
self.start_nats()
async def error_cb(self, e):
print(f'NATS: There was an error: {e}')
async def connected_cb(self):
print('NATS: Connected!')
async def start_nats(self):
try:
self.nc = await connect(
servers=self.servers,
token=self.token,
error_cb=self.error_cb,
connected_cb=self.connected_cb,
loop=self.loop
)
print('Application NATS started')
except errors.ErrNoServers:
print('NATS: No servers available for connection')
async def publish(self, subscribe, data):
text = json.dumps(data).encode('utf-8')
await self.nc.publish(subscribe, text)
async def close(self):
await self.nc.close()
nats_client = NatsClient(
token=NATS_AUTH_TOKEN,
servers=f'{NATS_HOST}:{NATS_PORT}'
)
# consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer
class NatsConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
async def disconnect(self, close_code):
pass
async def receive(self, text_data):
data = json.loads(text_data)
await nats_client.publish(data['subject'], data['message'])
|
I encountered a similar issue and ended up writing a sidecar service in Go (hats), which makes it easy for Django/DRF (or other Web) applications to communicate with NATS using HTTP. |
Hello friends! Thanks for the detailed documentation. But I need advice!
I have a service with a lot of docker images) Some of them work on django - rest_framework, and many of them on asyncio.
I need to communicate between images via http. But part of the communication I wanted to do was through the nuts.
Connecting nuts to those images that are built on asyncio was no problem, everything works great!
Has anyone connected nuts to django?
If all asynchronous requests are wrapped in a loop, they often fall off. I think it's Django's fault and of course my clumsy hands :) Below I will give what I have now and I don't like it...
The client that I made in django, and I import an instance of the class of this client where I want to send a message through the nats
So, please advise how to make friends between django and nats.
The text was updated successfully, but these errors were encountered: