如何在 Flask / gunicorn / gevent 中启动异步函数?
How can I start an asynchronous function in Flask / gunicorn / gevent?
我目前有一个 Flask 应用程序
from flask import Flask
import time
app = Flask(__name__)
@app.route('/')
def foobar_view():
long_running() # TODO: Just trigger this; don't wait for completion
return 'Done!'
def long_running():
print('long_running:start')
time.sleep(100)
print('long_running:end')
app.run(host='localhost', port=5000)
开始于
gunicorn --worker-class=gevent \
--worker-connections=1000 \
--bind 0.0.0.0:5000 my_app.app:app \
--workers=4 \
--timeout 120 \
--keep-alive 120
应用不会有大负载,这个long_running
功能只会很少被触发。我正在寻找一种 运行 的简单方法,并且我愿意接受有关 gunicorn / gevent 的更改。我正在使用 Python 3.7.
如何让 long_running
异步执行?
解决方案可能是 运行 线程中的 int:
from flask import Flask
import time
from threading import Thread
app = Flask(__name__)
@app.route('/')
def foobar_view():
Thread(target=async_long_running, args=(app, 'works')).start()
return 'Done!'
def async_long_running(app, msg):
with app.app_context():
long_running(msg)
def long_running(foo):
print('long_running:start:{}'.format(foo))
time.sleep(100)
print('long_running:end')
app.run(host='localhost', port=5000)
我目前有一个 Flask 应用程序
from flask import Flask
import time
app = Flask(__name__)
@app.route('/')
def foobar_view():
long_running() # TODO: Just trigger this; don't wait for completion
return 'Done!'
def long_running():
print('long_running:start')
time.sleep(100)
print('long_running:end')
app.run(host='localhost', port=5000)
开始于
gunicorn --worker-class=gevent \
--worker-connections=1000 \
--bind 0.0.0.0:5000 my_app.app:app \
--workers=4 \
--timeout 120 \
--keep-alive 120
应用不会有大负载,这个long_running
功能只会很少被触发。我正在寻找一种 运行 的简单方法,并且我愿意接受有关 gunicorn / gevent 的更改。我正在使用 Python 3.7.
如何让 long_running
异步执行?
解决方案可能是 运行 线程中的 int:
from flask import Flask
import time
from threading import Thread
app = Flask(__name__)
@app.route('/')
def foobar_view():
Thread(target=async_long_running, args=(app, 'works')).start()
return 'Done!'
def async_long_running(app, msg):
with app.app_context():
long_running(msg)
def long_running(foo):
print('long_running:start:{}'.format(foo))
time.sleep(100)
print('long_running:end')
app.run(host='localhost', port=5000)