小陆同学

python 中文名:蟒蛇,设计者:Guido van Rossum

导航

flask+vue--socketio的使用

   Socket.IO 就是一个封装了 Websocket、基于 Node 的 JavaScript 框架,包含 client 的 JavaScript 和 server 的 Node(现在也支持python,go lang等语言)。其屏蔽了所有底层细节,让顶层调用非常简单,另外,Socket.IO 还有一个非常重要的好处。其不仅支持 WebSocket,还支持许多种轮询机制以及其他实时通信方式,并封装了通用的接口。这些方式包含 Adobe Flash Socket、Ajax 长轮询、Ajax multipart streaming 、持久 Iframe、JSONP 轮询等。换句话说,当 Socket.IO 检测到当前环境不支持 WebSocket 时,能够自动地选择最佳的方式来实现网络的实时通信,这一点就比websocket要智能不少。

https://v3u.cn/a_id_158

https://www.cnblogs.com/dreamsqin/p/12018866.html

场景:flask+vue基于jenkins做应用构建,前端将需要的参数传递给后端,并由后端执行调用jenkins的方法,并且持续获取jenkins的构建日志,并返回给前端页面显示,最终将构建日志入库

后端:ps:目前发现的问题是,貌似只能将socketio的接口写到启动程序的文件里

#coding=utf8
import os
import unittest
import json
from flask import request
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager
from app import blueprint
from app.main import create_app, db
from flask_cors import CORS
from flask_socketio import SocketIO,send,emit
import urllib.parse

from app.main.model import *

app = create_app('dev')
app.register_blueprint(blueprint)
CORS(app, resources=r'/*')
socketio = SocketIO(app,cors_allowed_origins='*')

app.app_context().push()

manager = Manager(app)

migrate = Migrate(app, db)

manager.add_command('db', MigrateCommand)

from app.main.service.app_service import jenkins_job_build,check_app_build_consolelog,cancel_jenkins_job,app_deploy_job
from app.main.service.celerytask import save_jenkins_build_job_log,back_up_build_production_backage
# jenkins应用构建
@socketio.on('jenkins_build')
def jenkins_build_start(message,sid):
    message = json.loads(urllib.parse.unquote(message))
    response = jenkins_job_build(message)
    if response.get('code')==200:
        thread = socketio.start_background_task(target=background_thread_get_build_info,kwargs=response,sid=sid)
    else:
        socketio.emit('jenkins_build_console', {'text': response},room=sid,broadcast=True)

# 定时获取jenkins构建日志
def background_thread_get_build_info(sid,**kwargs):
    finish = 0
    while True:
        check_args = kwargs.get('kwargs').get('msg')
        tail_output,status = check_app_build_consolelog(check_args)
        if tail_output:
            print("'====='")
            print("finish",finish)
            tail_output = tail_output+'<br/>加载中...'
            socketio.emit('jenkins_build_console', {'text': {'code':200,'msg':tail_output}},room=sid, broadcast=True)
            if status and not finish:
                finish = 1continue
            elif status and finish:
                tail_output = tail_output + '<br/>构建结束!'
                socketio.emit('jenkins_build_console', {'text': {'code': 200, 'msg': tail_output}},room=sid,broadcast=True)
                build_result = {}
                build_result['log_detail'] = tail_output
                build_result['status'] = status
                build_result['app_name'] = check_args.get('app_name')
                build_result['job_id'] = check_args.get('job_id')
                build_result['app_id'] = check_args.get('app_id')
                task = save_jenkins_build_job_log(build_result)
                task = save_jenkins_build_job_log.delay(build_result)
                backup_result = back_up_build_production_backage.delay(check_args)
                print(task.id)
                break
        socketio.sleep(5)

@socketio.on('connect', namespace='/chat')
def test_connect():
    emit('my response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/chat')
def test_disconnect():
    print('Client disconnected')
@manager.command
def run():
    # app.run(port=8000, host="0.0.0.0")

    socketio.run(app, debug=True, host="0.0.0.0", port=5000)


if __name__ == '__main__':
    manager.run()

前端:

  created() {

    this.handleClick()
  },
  sockets:{
    // 建立socket连接
    connect: function(){
      console.log('socket 连接成功')
    },
    // 接收应用构建日志
    jenkins_build_console: function(val){
      console.log('=====')
      console.log(val)
      if (val['text']['code']!=200){
        alert(val['text']['msg'])
      }else{
        document.getElementById('app_build_logs').innerHTML=val['text']['msg']
      }
    },
  },
  methods: {
this.$socket.emit('jenkins_build',encodeURI(JSON.stringify(params)),this.$socket.id)

附jenkins的基本使用,更多可看jenkins模块的内置方法

import jenkins

"""
双引号 &quot;
单引号 &apos;
"""

server = jenkins.Jenkins('http://localhost:9090',username='admin',password='admin')
# # print(server.jobs_count())
# # server.create_job('empty', jenkins.RECONFIG_XML)
empty = server.get_job_config("abcc-test-java")
# # empty = server._get_view_jobs("视图h")
# # empty = server.get_view_name("项目2")
# empty = server.get_view_config("视图h")
# # empty = server.get_view_name("test_views2_project1")
print(empty)

# joblog=server.get_build_console_output("abcc-test",13)
# try:
#     joblog=server.stop_build("abcc-test",41)
# except Exception as e:
#     joblog='1111'
# joblog=server.get_job_info("abcc-test")['result']
# joblog=server.get_build_info("abcc-test",41)['result']
# print(joblog)
# print(type(joblog))
# reconfig_job

# view = server.view_exists('test_views2')
# view = server.create_view('test_views2')
# view = server.get_view_config('test_views2')
# print(view)

 遇到过的问题:

建立双工通讯后,前端页面报错:has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource。

乍一看是跨域问题,后来跟百度大神的学习和尝试都不行。
flask项目启动后提示客户端的版本不正确
The client is using an unsupported version of the Socket.IO or Engine.IO pro
但是前端vue换了多种方式,仍然不行,socket.io版本尝试了2.1.0和2.1.1
看了博客:
https://blog.csdn.net/lockhou/article/details/117917879后,尝试变更后端的库

使用pip3,将相关python包升级到指定版本 Flask-SocketIO3.0.2, python-engineio3.13.2, python-socketio==4.2.0

posted on 2022-04-20 19:51  小陆同学  阅读(736)  评论(0编辑  收藏  举报