flask-apscheduler和flask-socketio中的坑与解决方法

赫连琦
2023-12-01


flask-apscheduler和gunicorn, 及flask-socketio和gunicorn混用只能开启一个进程,

但是可以通过多线程同时调用两个服务多个进程启动flask服务_Peanut_范的博客-CSDN博客_flask 多进程

# -*- coding: utf-8 -*-
"""
-------------------------------------------------
  File Name:   23
  Description :
  Author :    xxx
  date:     2022/12/2
-------------------------------------------------
  Change Activity:
          2022/12/2:
-------------------------------------------------
"""
# cpu_and_mem_monitor
# 参考别人的代码,学习实践
# 思路:后端后台一旦产生数据,即刻推送到前端

from flask import Flask, render_template, session, request
import multiprocessing as mp
# socketio
from flask_socketio import SocketIO, emit

# threading
from threading import Lock

# 用于内存、时间等获取的库
import psutil
import time


####################

from datetime import datetime
from apscheduler.schedulers.blocking import BlockingScheduler

#################

async_mode = None

# 初始化一个flask应用
app = Flask(__name__)
# 进行session秘钥配置
app.config['SECRET_KEY'] = 'asdfsf'
socketio = SocketIO(app, async_mode=async_mode)

thread = None
thread_lock = Lock()


# 后台线程,采集计算机数据,实时推送给前端
def background_thread():
    count = 0
    while True:
        socketio.sleep(2)
        count = count + 1
        t = time.strftime('%M:%S', time.localtime())  # 获取系统时间,此处只取分秒
        cpus = psutil.cpu_percent(interval=None, percpu=True)  # 获取系统cpu使用率 non-blocking
        socketio.emit('server_response',
                      {'data': [t] + list(cpus)[0:4], 'count': count},
                      namespace='/test')  # 不需要客户端连接上下文,默认broadcast = True

        print([t] + list(cpus)[0:4])
        print( {'data': [t] + list(cpus)[0:4], 'count': count})
        print(100 * '*')


####

@app.route('/')
def index():
    return render_template('index.html', async_mode=socketio.async_mode)
    # 每次执行render_template函数时,渲染器都会将index.html的变量值用实际值替代。


# 与前端建立socket连接后,启动后台线程
@socketio.on('connect', namespace='/test')
def index_connect():
    global thread
    with thread_lock:
        if thread is None:
            thread = socketio.start_background_task(target=background_thread)

def startServer1(inDebug, port1):
    print("Starting Main Mock Server1")
    # app1.run(debug=inDebug, port=port1)
    socketio.run(app, debug=True,port=6001)


def job_func():
    print("当前时间:", datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f"))


def start_jobs(a,b):
    print('start_jobs 1')
    scheduler = BlockingScheduler()

    # 每2小时触发
    # scheduler.add_job(job_func, 'interval', hours=2)

    # 在 2019-04-15 17:00:00 ~ 2019-12-31 24:00:00 之间, 每隔两分钟执行一次 job_func 方法
    # scheduler.add_job(job_func, 'interval', minutes=2, start_date='2022-04-29 17:00:00', end_date='2022-12-31 24:00:00')
    # 每小时(上下浮动120秒区间内)运行`job_function`
    # scheduler.add_job(job_func, 'interval', hours=1, jitter=120)
    scheduler.add_job(job_func, 'interval',seconds=5)
    scheduler.start()



if __name__ == "__main__":
    p = mp.Process(target=startServer1, args=(False, 8082))
    p.deamon = True
    p.start()
    p1 = mp.Process(target=start_jobs, args=(False, 8083))
    p1.deamon = True
    p1.start()
    p.join()
    p1.join()
 类似资料: