如何为Blask App.run()设置启动处理程序



我没有找到一种设置处理程序来检测烧瓶服务器何时运行的方法。考虑以下代码段:

import flask
import requests
def on_start():
    # send a request to the server, it's safe to do so
    # because we know it's already running
    r = requests.get("http://localhost:1234")
    print(r.text) # hello world
app = flask.Flask(__name__)
@app.route("/")
def hello():
    return "hello world"
app.run(port=1234, host="localhost", on_start=on_start)

最后一行之所以失败,是因为on_start不是run的参数,但希望您能了解我要做什么。我该怎么做?

您能做的就是将要使用before_first_request装饰仪启动的功能包装,如下所示==> http://flask.pocoo.org/docs/1.0/api/#flask.flask.before_first_request

但是,直到有人向服务器提出请求,它才能启动,但是您可以做这样的事情:

import requests
import threading
import time
from flask import Flask
app = Flask(__name__)
@app.before_first_request
def activate_job():
    def run_job():
        while True:
            print("Run recurring task")
            time.sleep(3)
    thread = threading.Thread(target=run_job)
    thread.start()
@app.route("/")
def hello():
    return "Hello World!"

def start_runner():
    def start_loop():
        not_started = True
        while not_started:
            print('In start loop')
            try:
                r = requests.get('http://127.0.0.1:5000/')
                if r.status_code == 200:
                    print('Server started, quiting start_loop')
                    not_started = False
                print(r.status_code)
            except:
                print('Server not yet started')
            time.sleep(2)
    print('Started runner')
    thread = threading.Thread(target=start_loop)
    thread.start()
if __name__ == "__main__":
    start_runner()
    app.run()

详细信息&来源通过Google-Fu:https://networklore.com/start-task-with-flask/

最新更新