前端VUE:
<template>
<div class="common-layout">
<el-container>
<el-header
><el-row>
<el-col :span="24"
><div>
<strong style="font-size: larger">123</strong>
</div></el-col
>
</el-row>
<el-row>
<el-col :span="24">
<div>
<el-button type="success" @click="startCollection"
>启动</el-button
>
<el-button type="danger" @click="stopCollection">停止</el-button>
</div></el-col
>
</el-row>
</el-header>
<el-main>
<el-row>
<el-col :span="24">
<div>
<el-table :data="tableData" border style="width: 100%">
<el-table-column
prop="id"
label="ID"
align="center"
width="80"
/>
<el-table-column
prop="地址"
label="地址"
align="center"
width="150"
/>
<el-table-column
prop="值"
label="值"
align="center"
width="150"
/>
<el-table-column
prop="数据类型"
label="数据类型"
align="center"
width="150"
/>
<el-table-column
prop="功能"
label="功能"
align="center"
width="150"
/>
<el-table-column
prop="描述"
label="描述"
align="center"
width="300"
/>
<el-table-column
prop="time"
label="时间"
align="center"
width="300"
/>
</el-table>
</div>
</el-col>
</el-row>
</el-main>
</el-container>
</div>
</template>
<script setup>
import { ref } from "vue";
import API from "../utils/request";
var tableData = ref([]);
var eventSource = null;
function startCollection() {
API.post("/state/", {
aaa: "开始采集",
}).then(function (res) {
console.log(res);
});
if (!eventSource) {
eventSource = new EventSource("http://127.0.0.1:8000/sse_endpoint");
console.log("连接已建立");
eventSource.onmessage = function (event) {
var data = JSON.parse(event.data);
if (tableData.value.length == 11) {
tableData.value.length = 0;
}
tableData.value.push(data);
};
eventSource.onerror = function () {
eventSource.close();
eventSource = null;
};
}
}
function stopCollection() {
if (eventSource) {
eventSource.close();
eventSource = null;
}
API.post("/state/", {
aaa: "停止采集",
}).then(function (res) {
console.log(res);
});
}
</script>
<style>
.table {
overflow: hidden;
}
</style>
Django后端:
urls.py
from django.contrib import admin
from django.urls import path
from App01.views import sse_endpoint, state
urlpatterns = [
path('admin/', admin.site.urls),
path('sse_endpoint', sse_endpoint,name='sse_endpoint'),
path('state/', state,name='state'),
view.py
def sse_endpoint(request):
def event_stream():
while True:
# 在这里替换为获取最新数据的代码
data_list = []
cpList = DB3000_act01.objects.all()
# cpList = DB3000_act01.objects.all().order_by('-id')
for i in cpList:
data = {
"id": i.id,
"地址": i.地址,
"值": i.值,
"数据类型": i.数据类型,
"功能": i.功能,
"描述": i.描述,
"time": str(i.time)
}
data_list.append(data)
for data in data_list:
yield 'data: {}\n\n'.format(json.dumps(data))
time.sleep(0.05) # 休眠5秒钟,模拟实时数据更新
response = StreamingHttpResponse(event_stream(), content_type='text/event-stream')
response['Cache-Control'] = 'no-cache'
return response
sse_endpoint :每隔50ms向前端发送数据