I’ ll post in this section the full error, since the “title” section has a characters size constraint. Here it is: ValueError: The view test_app.views.sse_stream didn’t return an HttpResponse object. It returned an unawaited coroutine instead. You may need to add an ‘await’ into your view.
I am trying to use SSE ( server sent event ) to make a real time update of some data from my database (i am using the Django framework ). It won’t work as i get the prewies mentioned error. No matter what i have tried, i still get the same error.
Here is my view, and the function that i use to fetch data from the database:
`@sync_to_async
def retrievenotes(id_request):
#logging.logger.debug(f”Retrieving notes for id_request: {id_request}”)
notes = Note.objects.filter(random_id=id_request).order_by(‘-created_at’)
return list(notes)
@csrf_exempt
async def sse_stream(request, username):
“””
Sends server-sent events to the client.
“””
#logging.logger.debug(“Starting sse_stream”)
async def event_stream():
while True:
# Call the sync function asynchronously
notes = await retrievenote(‘wCgS8VVO0UY8fb4mAv0A’)
notes_str = “”.join([f”Note created at: {note.created_at}, Note text: {note.text}
” for note in notes])
yield await f"data: {notes_str}nn"
await asyncio.sleep(1)
# Convert the async generator to an async iterator
async def async_iterator_wrapper(async_gen):
async for item in async_gen:
yield await item
return StreamingHttpResponse(async_iterator_wrapper(event_stream()), content_type='text/event-stream')`
And here is the javascript code:
`
let eventSource;
const sseData = document.getElementById(‘notestext’);
function startSSE() {
var currentUrl = window.location.href;
console.log("Current URL: " + currentUrl);
// Construct the correct EventSource URL by appending '/stream/' to the base URL
const eventSourceUrl = `${currentUrl}stream/`;
// Initialize the EventSource object
eventSource = new EventSource(eventSourceUrl);
eventSource.onmessage = event => {
sseData.innerHTML = event.data;
console.log("sse data: " + event.data); // Log the received data
};
document.querySelector('button[onclick="startSSE()"]').disabled = true;
document.querySelector('button[onclick="stopSSE()"]').disabled = false;
}
function stopSSE() {
if (eventSource) {
eventSource.close();
console.log("EventSource closed");
}
document.querySelector('button[onclick="startSSE()"]').disabled = false;
document.querySelector('button[onclick="stopSSE()"]').disabled = true;
}
</script>`
I have tried to implement the same code in a new django project and it works without an issue (i have setup the SSE system the exact same way in both projects). I also tried to delete some middlewares, but still no luck.