Flask APP-ValueError:信号仅在主线程中有效

时间:2018-11-28 14:45:12

标签: python python-3.x web flask

我尝试创建一个简单的烧瓶应用程序:

from flask import Flask

app = Flask(__name__)

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

但是当我添加调试时:

FLASK_APP = run.py
FLASK_ENV = development
FLASK_DEBUG = 1

我遇到以下错误:

ValueError:信号仅在主线程中起作用

这里是完整的堆栈跟踪

FLASK_APP = run.py
FLASK_ENV = development
FLASK_DEBUG = 1
In folder c:/MyProjectPath/api
c:\MyProjectPath\api\venv\Scripts\python.exe -m flask run
 * Serving Flask-SocketIO app "run.py"
 * Forcing debug mode on
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 283-122-745
Exception in thread Thread-1:
Traceback (most recent call last):
  File "c:\appdata\local\programs\python\python37\Lib\threading.py", line 917, in _bootstrap_inner
    self.run()
  File "c:\appdata\local\programs\python\python37\Lib\threading.py", line 865, in run
    self._target(*self._args, **self._kwargs)
  File "c:\MyProjectPath\api\venv\lib\site-packages\flask_socketio\cli.py", line 59, in run_server
    return run_command()
  File "c:\MyProjectPath\api\venv\lib\site-packages\click\core.py", line 764, in __call__
    return self.main(*args, **kwargs)
  File "c:\MyProjectPath\api\venv\lib\site-packages\click\core.py", line 717, in main
    rv = self.invoke(ctx)
  File "c:\MyProjectPath\api\venv\lib\site-packages\click\core.py", line 956, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "c:\MyProjectPath\api\venv\lib\site-packages\click\core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "c:\MyProjectPath\api\venv\lib\site-packages\click\decorators.py", line 64, in new_func
    return ctx.invoke(f, obj, *args, **kwargs)
  File "c:\MyProjectPath\api\venv\lib\site-packages\click\core.py", line 555, in invoke
    return callback(*args, **kwargs)
  File "c:\MyProjectPath\api\venv\lib\site-packages\flask\cli.py", line 771, in run_command
    threaded=with_threads, ssl_context=cert)
  File "c:\MyProjectPath\api\venv\lib\site-packages\werkzeug\serving.py", line 812, in run_simple
    reloader_type)
  File "c:\MyProjectPath\api\venv\lib\site-packages\werkzeug\_reloader.py", line 267, in run_with_reloader
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
  File "c:\appdata\local\programs\python\python37\Lib\signal.py", line 47, in signal
    handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
ValueError: signal only works in main thread

2 个答案:

答案 0 :(得分:14)

您面临的问题与Flask-SocketIO软件包中的错误有关,该软件包取代了flask run命令。因此,即使您不导入Flask-SocketIO,也始终使用它。有几种解决方案:

  1. 卸载Flask-SocketIO
  2. 请勿使用flask run,而是运行程序的主文件
  3. 禁用调试
  4. 如果需要调试,请禁用自动加载flask run --no-reload

关于Flask-SocketIO错误的参考:issue 817

答案 1 :(得分:1)

我通过github上的@ AkshayKumar007 answer解决了这个问题。这对我来说是最方便的解决方案。

  

大家好,我也面临着同样的问题。所以总结一下,如果   您正在使用socket-io,请不要执行flask运行。首先,添加

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

在您的应用程序结尾。要运行它

python3 __init__.py
     

希望有帮助。