gpt4 book ai didi

uWSGI 上的 flask-socketio

转载 作者:行者123 更新时间:2023-12-05 07:07:37 27 4
gpt4 key购买 nike

我有这个 flask-socketio 应用

(venv) ubuntu@ip-172-31-18-21:~/code$ more app.py
from flask_socketio import SocketIO, send, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from time import sleep
from threading import Thread, Event

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app, async_mode='gevent')

thread = Thread()
thread_stop_event = Event()

def firstFunction():
print("*** First function")

def backgroundTask():
while not thread_stop_event.isSet():
socketio.emit('bg-socketio', {'data':'background-data'}, namespace='/', broadcast=True)
socketio.sleep(2)

def startBackgroundTask():
global thread

if not thread.is_alive():
thread = socketio.start_background_task(backgroundTask)

@app.route('/')
def main():
return render_template('index.html', title='SocketIO')

@socketio.on('connect_event', namespace='/')
def handle_message_client_connected(message):
print("*** Client connected")
emit('c-socketio', {'data':' you connected!'}, namespace='/')

if __name__ == '__main__':
firstFunction()
startBackgroundTask()
socketio.run(app, host='0.0.0.0', port=5000)

我希望 firstFunction() 和 startBackgroundTask() 在应用启动时运行。

在 uWSGI 上运行它的最佳实践是什么?我一直在尝试这样做但没有成功,不断出错 https://flask-socketio.readthedocs.io/en/latest/#uwsgi-web-server

错误:* 运行 gevent 循环引擎 [addr:0x5561d3f745a0] *该死 ! worker 1 (pid: 13772) 死了 :( 试图重生... worker 重生太快了!!!我得睡一会儿(2 秒)...重生 uWSGI worker 1(新 pid:13773)

也试过这个

uwsgi --socket 0.0.0.0:5000 --protocol=http --enable-threads -w wsgi:app

(venv) ubuntu@ip-172-31-18-21:~/code$ more wsgi.py
from uapp import app

if __name__ == "__main__":
app.run()

将 uapp.py 更改为

if __name__ == '__main__':
firstFunction()
startBackgroundTask()
app.run(host='0.0.0.0', port=5000)

但这不会运行 firstFunction() 或 startBackgroundTask()

我几乎卡住了,正在寻找一些建议。

最佳答案

你的问题的简单答案是改变这个:

if __name__ == '__main__':
firstFunction()
startBackgroundTask()
app.run(host='0.0.0.0', port=5000)

为此:

firstFunction()
startBackgroundTask()

if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)

不过,您还有一些其他问题需要解决。

async_mode 变量设置为gevent,但您正在使用 uWSGI 作为服务器。将其更改为 gevent_uwsgi 或将其删除,以便在运行时自动为您设置。

文档中显示了使用 uWSGI 启动 Flask-SocketIO 应用程序的命令:

uwsgi --http :5000 --gevent 1000 --http-websockets --master --wsgi-file app.py --callable app

您还需要安装 gevent

关于uWSGI 上的 flask-socketio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62078367/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com