Hi, I’m building REST API using Django Rest Framework but I need to have a real-time functionality. Is it possible to integrate Django Channels with Django Rest Framework ? I will need e.g authentication from DRF to vote using Django Channels is it possible ?
What sort of integration are you talking about here?
Yes, there are parts of DRF that may make sense in channels (e.g. serializers), and there are parts of DRF that wouldn’t make sense in channels (e.g. views).
DRF is a Django module. As such, it’s designed around the traditional “Request / response” cycle of an HTTP request.
Channels is built around communications through a WebSocket - a single HTTP request that gets “upgraded”. Since it’s a persistent connection, the authentication occurs once when the connection is established. It does support standard Django authentication out-of-the-box.
How comfortable are you with the protocol differences between Http and WebSockets?
I don’t know how to response you so I will describe what I want to achieve.
There will be two parts of application.
First part that doesn’t need to be realtime. There will be features like: authentication (JWT), endpoint like create_pool, etc…
Second part - voting system I want to give users possibility to vote on created pools in REAL-TIME
My question is: Can I use both DRF and Django-Channels in one application, If yes how the project structure should look because I have’t found any good examples.
You can use both in one application, because there’s no real direct interface between the two.
You build your DRF project just like you would build any other DRF project.
You build your Channels application just like you would build any other Channels application.
If your Channels application needs to call a function from your DRF project, then the Channels consumer would import that function and call it - just like it could call any other function.
Just keep in mind that your Channels application has no reason to call a DRF View.
Also take a look at LostMoa/Djangochannelsrestframework: A Rest-Framework for Websockets Using Django Channels-v3 which integrates DRF and Channels. At the very least you’ll get ideas from that (if not exactly what you’re after).
BTW, this is linked from Community Projects — Channels 3.0.4 Documentation which is worth looking at too.