Bob Sacamano
Bob Sacamano

Reputation: 439

Django: real time database using channels

I'm looking into channels lately in Django and from what I see in all the examples it is used for chat like applications. But I was wondering if I can use it to push notifications about database changes.

So for example, what if my "view" consumer would poll the database and push notification every time it changed to the client. It is as if all clients of that page connect to the same chat room and wait for "posts" from the server.

I know I can poll from the client using Ajax but I was wondering if I can use Django channels for that and have the server do the polling.

Upvotes: 2

Views: 2036

Answers (1)

Matthaus Woolard
Matthaus Woolard

Reputation: 2408

In your case if its just a chat room your better not observing the db directly but sending a message over the channel layers when a message is posted/updated https://channels.readthedocs.io/en/latest/topics/channel_layers.html you can do this from anywere in your django code.

Then any WS consumers that have subscribed to those layer groups will be informed of a change.

If you have a more complex situation with many different models to observe:

You do not need to Poll the database, (as long as all the changes made to the db are made through django's ORM).

Here is a lib https://github.com/hishnash/djangochannelsrestframework that supports subscribing to objects in your db.

With this you can subscribe to the changes in the db, it also adds some other helper functions so that you can re-use existing django rest framework code you might have in your project.

Upvotes: 1

Related Questions