实现 Python 服务在执行完毕后主动向前端发送信息,以便前端(比方 Vue.js ...

打印 上一主题 下一主题

主题 504|帖子 504|积分 1512

可以通过多种方法实现 Python 服务在执行完毕后主动向前端发送信息,以便前端(比方 Vue.js 应用)可以更新显示。下面介绍几种常见的方法:
1. 使用 WebSockets

WebSockets 是一种在客户端和服务器之间建立长期连接的通信协议,适用于实时更新。可以使用 websockets 库在 Python 中实现 WebSocket 服务器。
Python 服务器代码示例:

  1. import asyncio
  2. import websockets
  3. async def handler(websocket, path):
  4.     while True:
  5.         # 等待客户端请求
  6.         message = await websocket.recv()
  7.         print(f"Received message: {message}")
  8.         # 执行某些操作...
  9.         
  10.         # 发送更新通知给前端
  11.         await websocket.send("Update completed")
  12. start_server = websockets.serve(handler, "localhost", 6789)
  13. asyncio.get_event_loop().run_until_complete(start_server)
  14. asyncio.get_event_loop().run_forever()
复制代码
Vue.js 前端代码示例:

  1. <template>
  2.   <div>
  3.     <p>{{ message }}</p>
  4.   </div>
  5. </template>
  6. <script>
  7. export default {
  8.   data() {
  9.     return {
  10.       message: 'Waiting for update...'
  11.     };
  12.   },
  13.   created() {
  14.     this.connectWebSocket();
  15.   },
  16.   methods: {
  17.     connectWebSocket() {
  18.       const socket = new WebSocket('ws://localhost:6789');
  19.       socket.onmessage = (event) => {
  20.         this.message = event.data;
  21.       };
  22.     }
  23.   }
  24. };
  25. </script>
复制代码
2. 使用 HTTP Polling

HTTP Polling 是一种客户端定期向服务器发送请求以检查是否有新数据的技能。固然不如 WebSockets 实时,但实现简单且兼容性好。
Python 服务器代码示例:

  1. from flask import Flask, jsonify
  2. import time
  3. app = Flask(__name__)
  4. @app.route('/check_update', methods=['GET'])
  5. def check_update():
  6.     # 模拟一些处理
  7.     time.sleep(5)
  8.     return jsonify({'status': 'Update completed'})
  9. if __name__ == '__main__':
  10.     app.run(debug=True)
复制代码
Vue.js 前端代码示例:

  1. <template>
  2.   <div>
  3.     <p>{{ message }}</p>
  4.   </div>
  5. </template>
  6. <script>
  7. export default {
  8.   data() {
  9.     return {
  10.       message: 'Waiting for update...'
  11.     };
  12.   },
  13.   created() {
  14.     this.checkForUpdate();
  15.   },
  16.   methods: {
  17.     checkForUpdate() {
  18.       setInterval(() => {
  19.         fetch('/check_update')
  20.           .then(response => response.json())
  21.           .then(data => {
  22.             this.message = data.status;
  23.           });
  24.       }, 5000); // 每5秒检查一次
  25.     }
  26.   }
  27. };
  28. </script>
复制代码
3. 使用 Server-Sent Events (SSE)

SSE 允许服务器主动推送消息到客户端。它基于 HTTP 协议,适用于需要频繁更新但不需要双向通信的场景。
Python 服务器代码示例:

  1. from flask import Flask, Response
  2. import time
  3. app = Flask(__name__)
  4. @app.route('/stream')
  5. def stream():
  6.     def event_stream():
  7.         while True:
  8.             time.sleep(1)
  9.             yield f'data: Update completed\n\n'
  10.     return Response(event_stream(), content_type='text/event-stream')
  11. if __name__ == '__main__':
  12.     app.run(debug=True)
复制代码
Vue.js 前端代码示例:

  1. <template>
  2.   <div>
  3.     <p>{{ message }}</p>
  4.   </div>
  5. </template>
  6. <script>
  7. export default {
  8.   data() {
  9.     return {
  10.       message: 'Waiting for update...'
  11.     };
  12.   },
  13.   created() {
  14.     this.connectSSE();
  15.   },
  16.   methods: {
  17.     connectSSE() {
  18.       const eventSource = new EventSource('/stream');
  19.       eventSource.onmessage = (event) => {
  20.         this.message = event.data;
  21.       };
  22.     }
  23.   }
  24. };
  25. </script>
复制代码
选择哪种方法取决于您的详细需求和应用场景。如果需要双向通信和实时性,WebSockets 是最佳选择。如果只需要服务器向客户端推送更新且无需双向通信,SSE 是一个不错的选择。如果实现简单是优先考虑的,HTTP Polling 也可以满足需求。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

写过一篇

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表