Receiving the data where? Are you saying your channels consumer is going to be making the rpc call, or are you saying the client browser is making that call? What’s the desired flow of data here?
Generally speaking, “pages” or “templates” don’t receive data. In the case of channels, the either the server or the browser receives “events” to be handled. In the browser, that means JavaScript.
from django.urls import re_path
from myproject.main import consumers
websocket_urlpatterns = [
re_path(r'ws/', consumers.Consumer.as_asgi()),
]
In the consumer.py I have async method which returns something using json-rpc. This method is called ‘get_file_tree’. When user select a folder , this method returns the root folder. I want to grab that return in one of the pages I am showing to client in the browser.
I saw one example on how to receive data:
<script>
var socket = new WebSocket('ws://localhost:8000/ws/');
socket.onmessage = function(event){
let path = event.data;
console.log(path);
}
</script>
But this is not working in my side.
Does that clear your question ?
So it looks like you’re opening the socket, but I don’t see where you’re initiating the json-rpc call to generate any kind of response. Nor do I see where you’re doing anything with the data being received to display it on the page.
If it’s being sent through the socket, then the server will know through which web socket the request was received, and can return the response through the same socket. However, if you’re initiating this call through http, I don’t see where the server is going to know which channel to respond to.
In the consumer.py I have declared a method which use [json-rpc api](https://github.com/millerf/django-channels2-jsonrpc)
@Consumer.rpc_method()
async def get_file_tree(arg1, arg2) :
// do sum stuff
return file_path
Like I mentioned, I have a explorerer.js, which handle this request in the server side and client_api.js which mirror and invoke the get_file_tree request in the front end. I can see the output in console. However, I want to use the returned path in html files. That I can not figure out.
You’re getting the response as a JavaScript event. It’s your JavaScript that needs to inject whatever desired display into your page. So this would be an exercise in DOM manipulation.
One option you do have is to have your server side component return the html text rendered using render_to_string and then have your JS inject that result directly into the page.
Or, if you’re just displaying an image in the file, you can return the url field of that image as a string and inject that into an img tag.
Either way (among others) its up to you to decide what data you’re returning and what you want to have the JavaScript in the browser do with it.