代码之家  ›  专栏  ›  技术社区  ›  Mei Zhang

如何设置烧瓶启动处理程序应用程序运行()

  •  0
  • Mei Zhang  · 技术社区  · 7 年前

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

    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 ,但希望你知道我想做什么。我该怎么做?

    0 回复  |  直到 7 年前
        1
  •  -1
  •   Carlos    7 年前

    你所能做的就是包装你想要启动的函数 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()
    

    https://networklore.com/start-task-with-flask/