当前位置:   article > 正文

python后端主动向vue前端发送socket数据_python推送数据到vue

python推送数据到vue

        常见的前后端交互协议都是前端发送请求,后端响应请求。但是想让后端直接推送内容到前端很难,而socket就能帮助我们解决这个问题,使得后端可以主动向前端推送数据

1.python后端发送数据

  1. socketio = SocketIO(app,async_mode ='eventlet',cors_allowed_origins='*')
  2. socketModel.init_socket(socketio)
  3. class SocketModel:
  4. def __init__(self):
  5. self.socketIO = None
  6. def init_socket(self,socketio):
  7. self.socketIO = socketio
  8. def send(self, data, json=False, namespace=None, room=None,
  9. callback=None, include_self=True, skip_sid=None, **kwargs):
  10. if self.socketIO:
  11. self.socketIO.send(data, json=json, namespace=namespace, room=room,
  12. callback=callback, include_self=include_self, skip_sid=skip_sid, **kwargs)
  13. def task(self,event, *args, **kwargs):
  14. self.socketIO.emit(event, *args, **kwargs)
  15. def emit(self, event, *args, **kwargs):
  16. if self.socketIO:
  17. self.socketIO.emit(event, *args, **kwargs)
  18. socketModel = SocketModel()
  19. socketModel.emit('webPhoneUpdate', body)
  20. socketModel.emit('webPhoneUpdateData', resultPhone)

 

2.vue前端接收数据并存入vuex中

main.js

  1. Vue.use(new VueSocketIO({
  2. debug: false,
  3. connection: 'http://localhost:5000',
  4. // cors_allowed_origins:'*',
  5. vuex: { // 不需要用到vuex这个可以不加
  6. store,
  7. actionPrefix: 'SOCKET_',
  8. mutationPrefix: 'SOCKET_'
  9. }
  10. }))

state.js

  1. const state = {
  2. phone_info : [],
  3. evidence_info : [],
  4. phone_imsi_info : [],
  5. }
  6. const mutations = {
  7. SOCKET_webPhoneUpdate: (state, data) => {
  8. state.phone_info.push(data);
  9. // state.phone_info.sort(state.phone_info.timestr)
  10. console.log('vuex get phone_info')
  11. },
  12. SOCKET_webEvidenceUpdate(state, data) {
  13. console.log('vuex get webEvidenceUpdate')
  14. state.evidence_info.push(data);
  15. },
  16. SOCKET_webPhoneUpdateData(state, data) {
  17. console.log('vuex get webPhoneUpdate')
  18. state.phone_imsi_info = data;
  19. console.log(state.phone_imsi_info)
  20. },
  21. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/66576
推荐阅读
相关标签
  

闽ICP备14008679号