Python 在单独的线程中启动烧瓶应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31264826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:43:39  来源:igfitidea点击:

Start a flask application in separate thread

pythonmultithreadingflask

提问by FunkySayu

I'm currently developing a Python application on which I want to see real-time statistics. I wanted to use Flaskin order to make it easy to use and to understand.

我目前正在开发一个 Python 应用程序,我想在其中查看实时统计信息。我想使用它Flask是为了使它易于使用和理解。

The issue is that my Flask server should start at the very beginning of my Python application and stop at the very end. It should look like this:

问题是我的 Flask 服务器应该在我的 Python 应用程序的最开始开始并在最后停止。它应该是这样的:

def main():
    """ My main application """
    from watcher.flask import app
    # watcher.flask define an app as in the Quickstart flask documentation.
    # See: http://flask.pocoo.org/docs/0.10/quickstart/#quickstart

    app.run() # Starting the flask application

    do_my_stuff()

    app.stop() # Undefined, for the idea 

Because I need my application context (for the statistics), I can't use a multiprocessing.Process. Then I was trying to use a threading.Thread, but it looks like Werkzeug doesn't like it:

因为我需要我的应用程序上下文(用于统计),所以我不能使用multiprocessing.Process. 然后我试图使用 a threading.Thread,但看起来 Werkzeug 不喜欢它:

 * Running on http://0.0.0.0:10079/
Exception in thread Flask Server:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File ".../develop-eggs/watcher.flask/src/watcher/flask/__init__.py", line 14, in _run
    app.run(host=HOSTNAME, port=PORT, debug=DEBUG)
  File ".../eggs/Flask-0.10.1-py2.7.egg/flask/app.py", line 772, in run
    run_simple(host, port, self, **options)
  File ".../eggs/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 609, in run_simple
    run_with_reloader(inner, extra_files, reloader_interval)
  File ".../eggs/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 524, in run_with_reloader
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
ValueError: signal only works in main thread

How can I do that without running Flask in the main thread?

如果不在主线程中运行 Flask,我该如何做到这一点?

采纳答案by Thomas Orozco

You're running Flaskin debug mode, which enables the reloader(reloads the Flask server when your code changes).

您正在Flask调试模式下运行,这将启用重新加载(当您的代码更改时重新加载 Flask 服务器)。

Flask can run just fine in a separate thread, but the reloader expects to run in the main thread.

Flask 可以在单独的线程中正常运行,但重载器希望在主线程中运行。



To solve your issue, you should either disable debug (app.debug = False), or disable the reloader (app.use_reloader=False).

要解决您的问题,您应该禁用调试 ( app.debug = False) 或禁用重新加载器 ( app.use_reloader=False)。

Those can also be passed as arguments to app.run: app.run(debug=True, use_reloader=False).

这些也可以作为参数传递给app.run: app.run(debug=True, use_reloader=False)

回答by Burhan Khalid

From the werkzeug documentation:

werkzeug文档

Shutting Down The Server

New in version 0.7.

Starting with Werkzeug 0.7 the development server provides a way to shut down the server after a request. This currently only works with Python 2.6 and later and will only work with the development server. To initiate the shutdown you have to call a function named 'werkzeug.server.shutdown' in the WSGI environment:

def shutdown_server(environ):
    if not 'werkzeug.server.shutdown' in environ:
        raise RuntimeError('Not running the development server')
    environ['werkzeug.server.shutdown']()

关闭服务器

0.7 版中的新功能。

从 Werkzeug 0.7 开始,开发服务器提供了一种在请求后关闭服务器的方法。这目前仅适用于 Python 2.6 及更高版本,并且仅适用于开发服务器。要启动关闭,您必须在 WSGI 环境中调用名为“werkzeug.server.shutdown”的函数:

def shutdown_server(environ):
    if not 'werkzeug.server.shutdown' in environ:
        raise RuntimeError('Not running the development server')
    environ['werkzeug.server.shutdown']()

回答by Rashid Mv

if you are looking for accessing ipython terminal in flask run your application in separate thread, try this example:-

如果您正在寻找在 Flask 中访问 ipython 终端在单独的线程中运行您的应用程序,请尝试以下示例:-

from flask import Flask                                                         
import thread
data = 'foo'
app = Flask(__name__)
@app.route("/")
def main():
    return data
def flaskThread():
    app.run()
if __name__ == "__main__":
    thread.start_new_thread(flaskThread,())

run this file in ipython

在 ipython 中运行这个文件

回答by skeller88

Updated answer for Python 3 that's a bit simpler:

更新了 Python 3 的答案,这有点简单:

from flask import Flask                                                         
import threading

data = 'foo'
app = Flask(__name__)

@app.route("/")
def main():
    return data

if __name__ == "__main__":
    threading.Thread(target=app.run).start()