如何为烧瓶app.run()设置启动时处理程序

时间:2019-02-16 05:22:18

标签: python flask

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

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的自变量,但是希望您对我正在尝试做的事情有所了解。我该怎么办?

1 个答案:

答案 0 :(得分:-1)

您可以做的是用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/