我正在编写一个程序来检索数据并将其显示在 Django 模板中。我有一个名为 match_algo() 的函数,它需要很长时间才能运行。我想最初在页面上显示“正在加载............”,一旦函数完成并返回结果,我想在页面上显示检索到的内容。
这是我首先尝试的视图:
def redirected_page(request):
data = match_algo()
context = {
'data' : json.dumps(data),
'test' : 'test'
}
return render(request , 'redirected_page.html' , context )
经过一些研究,我发现 WebSockets 可能会对此有所帮助,但我仍然不确定这是否是我需要的解决方案。
这是我的消费者.py:
class LoadingConsumer(AsyncWebsocketConsumer):
async def connect(self):
await self.accept()
# Send "loading..." message when the connection is established
await self.send(text_data=json.dumps({
'message': 'loading...',
"status" : False
}))
data = match_algo()
# Send "loading completed" message after processing is done
await self.send(text_data=json.dumps({
'message': "loaded",
"status" : True,
# "matches" : data
}))
# Close the connection after sending the final message
await self.close()
出于测试目的,我评论了这一行
data = match_algo()
然后添加
time.sleep(5)
。
这确实有效。但是当我在几秒钟后使用
match_algo
运行时,websockets
断开连接。但match_algo
功能有效。由于 websocket
连接正在关闭。我无法得到结果,也无法显示它。
有什么办法可以解决这个问题吗?或者还有什么更好的方法吗??
redirect.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Therapist Details</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
body {
margin : 80px 150px
}
</style>
</head>
<body>
<h1>Therapist Details</h1>
<div id="therapist-table-container">
Matching Therapist suitable for you. Please wait.
</div>
<script>
const loadingMessage = document.getElementById('loadingMessage');
const socket = new WebSocket('ws://' + window.location.host + '/ws/loading/');
socket.onopen = function(event) {
console.log('WebSocket opened with code:', event.code);
};
socket.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log(data.message)
console.log(data.matches)
if (data.status) {
const tableHTML = `
<table>
<thead>
<tr>
<th>Name</th>
<th>Specialty</th>
<th>Experience</th>
<th>Contact</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>Clinical Psychology</td>
<td>10 years</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>Marriage and Family Therapy</td>
<td>8 years</td>
<td>[email protected]</td>
</tr>
<tr>
<td>Michael Johnson</td>
<td>Child and Adolescent Therapy</td>
<td>12 years</td>
<td>[email protected]</td>
</tr>
</tbody>
</table>
`;
// Add the table to the DOM
const tableContainer = document.getElementById('therapist-table-container');
tableContainer.innerHTML = tableHTML;
} else {
// Hide the table if data.status is false
const tableContainer = document.getElementById('therapist-table-container');
tableContainer.innerHTML = 'Matching Therapist suitable for you. Please wait.';
}
};
socket.onclose = function(event) {
console.log('WebSocket closed with code:', event.code);
};
</script>
</body>
</html>
感谢您的宝贵时间
Websocket 是一个好方法。
Javascript Websocket https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
Python Websocket https://pypi.org/project/websockets/
发送/接收,实时任何数据,无需任何刷新,您可以使用像(document.getelement...)这样的Javascript并在接收任何值时更改html数据。