python如何在线程中运行flask应用程序?

时间:2019-07-02 15:53:20

标签: python multithreading flask

如何在单独的线程中运行烧瓶应用程序? 我可以在主目录中运行我的烧瓶应用程序,但是

我需要从一个线程启动flask应用程序,该线程应该在主线程中启动线程引擎启动事件的同时正在运行。

所以这很好

@app.route("/voice", methods=['GET', 'POST'])
def voice():
  .........
  return str(resp)

@app.route("/mainFlow", methods=['GET', 'POST'])
def mainFlow():
    """Respond """
    .......

    return str(resp)


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

但是我需要这样的东西

def myIVR():
    print("-----------------Thrd1-myIVR --------------------")
    app = Flask(__name__)
    app.run(debug=True)

    @app.route("/voice", methods=['GET', 'POST'])
    def voice():
      ........
      return str(resp)

    @app.route("/mainFlow", methods=['GET', 'POST'])
    def mainFlow():
        """Respond to """
        resp = VoiceResponse()

def myTest():
    print("E2Etest")
    thrd1 = threading.Thread(target=myIVR, args=[])
    thrd1.start()
    print("trigger event")
    #xyz()

################################################################
def main():
    myTest()

if __name__ == '__main__':
    main()

我收到此错误

  File "C:\......\AppData\Local\Programs\Python\Python37-32\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

1 个答案:

答案 0 :(得分:0)

尝试:

from flask import Flask                                                         
import threading
app = Flask(__name__)



def myIVR():
  print("-----------------Thrd1-myIVR --------------------")
  app = Flask(__name__)
  threading.Thread(target=app.run).start()

@app.route("/voice", methods=['GET', 'POST'])
def voice():
  return str(resp)

@app.route("/mainFlow", methods=['GET', 'POST'])
def mainFlow():
    """Respond to """
    resp = VoiceResponse()

def myTest():
  print("E2Etest")
  thrd1 = threading.Thread(target=myIVR, args=[])
  thrd1.start()
  print("trigger event")
#xyz()

################################################################
def main():
    myTest()

if __name__ == '__main__':
    main()

或在调试模式为False的情况下使用烧瓶,它将解决您的问题:

from flask import Flask                                                         
import threading
app = Flask(__name__)



def myIVR():
  print("-----------------Thrd1-myIVR --------------------")
  app = Flask(__name__)
  app.run(debug=False)

@app.route("/voice", methods=['GET', 'POST'])
def voice():
  return str(resp)

@app.route("/mainFlow", methods=['GET', 'POST'])
def mainFlow():
    """Respond to """
    resp = VoiceResponse()

def myTest():
  print("E2Etest")
  thrd1 = threading.Thread(target=myIVR, args=[])
  thrd1.start()
  print("trigger event")
#xyz()

################################################################
def main():
    myTest()

if __name__ == '__main__':
    main()