[英]How to set an on start handler for flask app.run()
I haven't found a way to set a handler to detect when a flask server is already running. 我还没有找到一种设置处理程序以检测Flask服务器何时已在运行的方法。 Consider the following code snippet:
考虑以下代码片段:
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)
The last line fails because on_start
is not an argument of run
, but hopefully you get the idea of what I'm trying to do. 最后一行失败,因为
on_start
不是run
的参数,但希望您对我正在尝试做的事情有所了解。 How can I do it? 我该怎么做?
What you can do is wrap the function that you want to kick off with before_first_request
decorator as found here ==> http://flask.pocoo.org/docs/1.0/api/#flask.Flask.before_first_request 您可以做的是使用
before_first_request
装饰器包装要启动的函数,如此处==> http://flask.pocoo.org/docs/1.0/api/#flask.Flask.before_first_request
However, it won't get kicked off until someone makes a request to the server but you can do something like this: 但是,除非有人向服务器发出请求,否则它不会启动,但是您可以执行以下操作:
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()
Details & Source via Google-fu: https://networklore.com/start-task-with-flask/ 通过Google-fu的详细信息和来源: https : //networklore.com/start-task-with-flask/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.