Flask 应用程序运行后调用函数的正确方法是什么?

发布于 2025-01-05 12:27:43 字数 969 浏览 1 评论 0原文

我对如何做一些我认为很简单的事情感到有点困惑。我有一个使用 Flask 编写的简单应用程序。它看起来像这样:

from flask import Flask

app = Flask(__name__)

def _run_on_start(a_string):
    print "doing something important with %s" % a_string

@app.route('/')
def root():
    return 'hello world'

if __name__ == "__main__":
    if len(sys.argv) < 2:
        raise Exception("Must provide domain for application execution.")
    else:
        DOM = sys.argv[1]
        _run_on_start("%s" % DOM)
        app.run(debug=True)

我发现我的终端正在输出 _run_on_start 中的打印语句,但不是其他常用的 Flask 应用程序调试代码。如果我在 app.run 之前删除调用,则输出正常。此外,我发现 _run_on_start 的输出在启动时重复两次,尽管我不知道这是一些奇怪的输出还是该函数实际上被调用了两次。

我假设这不是在调用 app.run 之前添加函数调用的正确方法。我查看了 Flask 文档,发现可以使用各种装饰器,这些装饰器允许您在某些请求之前/之后执行函数,但我想在应用程序服务器运行时执行调用。

此外,我意识到,如果我从另一个模块调用此模块,即不是在 __name__ != "__main__" my 时,我将不会收到对 _run_on_start 的调用。

这里正确的方法是什么?在这两种情况下,当我从 CL 和另一个模块开始时?

I'm a little confused about how to do something that I thought would be quite simple. I have a simple app written using Flask. It looks something like this:

from flask import Flask

app = Flask(__name__)

def _run_on_start(a_string):
    print "doing something important with %s" % a_string

@app.route('/')
def root():
    return 'hello world'

if __name__ == "__main__":
    if len(sys.argv) < 2:
        raise Exception("Must provide domain for application execution.")
    else:
        DOM = sys.argv[1]
        _run_on_start("%s" % DOM)
        app.run(debug=True)

What I'm finding is that my terminal is outputting the print statements in _run_on_start but non of the other usual Flask app debug code. If I remove the call before app.run, the output is normal. Further I'm finding the output of _run_on_start to be repeated twice on startup, though I don't know if it's some weird output or the function is actually being called twice.

I'm assuming this is not the right way to add a function call before you call app.run. I looked in the Flask docs and found mentions of various decorators one can use, which allow you to execute a function before/after certain requests but I want to execute the call when the app server is run.

Further, I realise that if I call this module from another module, i.e., not when __name__ != "__main__" my I won't get my call to _run_on_start.

What's the right approach here? In both cases when I'm starting from the CL and from another module?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

笔落惊风雨 2025-01-12 12:27:43

也许您正在寻找 Flask.before_first_request 装饰器,如下所示:

@app.before_first_request
def _run_on_start(a_string):
    print "doing something important with %s" % a_string

Probably you were looking for Flask.before_first_request decorator, as in:

@app.before_first_request
def _run_on_start(a_string):
    print "doing something important with %s" % a_string
不必你懂 2025-01-12 12:27:43

函数的重复输出可以由重新加载器解释。它所做的第一件事是在新线程中启动 main 函数,以便它可以监视源文件并在它们更改时重新启动线程。使用 use_reloader=False 选项禁用此功能。

如果您希望能够在从不同模块启动服务器时运行您的函数,请将其包装在一个函数中,然后从另一个模块调用该函数:

def run_server(dom):
        _run_on_start("%s" % dom)
        app.run(debug=True, use_reloader=False)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        raise Exception("Must provide domain for application execution.")
    else:
        DOM = sys.argv[1]
        run_server(DOM)

“正确的方法”取决于您实际想要在此处完成的任务。内置服务器用于在将应用程序部署到生产服务器之前在本地测试环境中运行应用程序,因此从不同模块启动它本身的问题没有多大意义。

The duplicate output from your function can be explained by the reloader. The first thing it does is start the main function in a new thread so it can monitor the source files and restart the thread when they change. Disable this with the use_reloader=False option.

If you want to be able to run your function when starting the server from a different module, wrap it in a function, and call that function from the other module:

def run_server(dom):
        _run_on_start("%s" % dom)
        app.run(debug=True, use_reloader=False)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        raise Exception("Must provide domain for application execution.")
    else:
        DOM = sys.argv[1]
        run_server(DOM)

The "right approach" depends on what you're actually trying to accomplish here. The built-in server is meant for running your application in a local testing environment before deploying it to a production server, so the problem of starting it from a different module doesn't make much sense on its own.

断爱 2025-01-12 12:27:43
from flask import Flask

def create_app():
    app = Flask(__name__)
    def run_on_start(*args, **argv):
        print "function before start"
    run_on_start()
    return app

app = create_app()

@app.route("/")
def hello():
    return "Hello World!"
from flask import Flask

def create_app():
    app = Flask(__name__)
    def run_on_start(*args, **argv):
        print "function before start"
    run_on_start()
    return app

app = create_app()

@app.route("/")
def hello():
    return "Hello World!"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文