我是Flask的新手,我想知道我们是否可以运行与Flask应用程序并行运行的不同类的不同进程。我的代码结构与此非常相似:
from flask import Flask, render_template, flash, request, jsonify
from flask_socketio import SocketIO, emit
from flask_wtf import FlaskForm
from wtforms import *
import multiprocessing as mp
import os
import serial
import time, datetime
# App config.
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = '7d441f27d441f27567d441f2b6176a'
app.config['DEBUG'] = True
#turn the flask app into a socketio app
socketio = SocketIO(app)
class serial_read_Process():
def __init__(self):
self.delay = 0.2
self.port = serial.Serial ( port='/dev/ttyTHS2', baudrate=115200,
parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS, timeout=1)
def serial_read (self):
# read UART and process the incoming serial data and send it to webpage
currtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
socketio.emit('values', {'data1':data1, 'currtime':currtime}, namespace='/serial')
time.sleep(self.delay)
class ProcessWebPageData():
def __init__(self, name):
self.person_name = name
self.delay = 0.2
def process_data(self):
# process the data received from the webpage
time.sleep(self.delay)
@socketio.on('my_event', namespace='/test')
def test_message(message):
name_val= message.get('name')
ProcessDataObj = ProcessWebPageData()
process2 = mp.Process(target=ProcessDataObj.process_data, args=(name_val,)) # For Processing the data received from the web page
if not process2.is_alive():
thread2.daemon = True
thread2.start()
@app.route("/", methods=['GET', 'POST'])
def load():
return render_template('index.html')
@socketio.on('connect', namespace='/test')
def test_connect():
print('Client connected')
uart_read = serial_read_Thread()
process1 = mp.Process(target=uart_read.serial_read) # For Reading UART values
process1.daemon = True
if not process1.is_alive():
process1.start()
print("process started")
if __name__== "__main__":
socketio.run(app)
当我在serial_read函数中打印那些值时,我不断从UART获取值,我看到它们正在打印。我在通过socketio.emit()发送的网页上看不到它们。我有一个Javascript代码,可以在其中接收值并使用它在HTML网页上显示。这也是正确的方法吗?任何输入将不胜感激。 TIA。