很简单的问题,我希望。我有一个需要收听订阅的烧瓶服务。我编写了所有代码来监听订阅并在触发时运行一些代码。
flask 应用程序代码是:
from flask import Flask, jsonify
import logging
from celery.bin.worker import worker
from celery import shared_task
from proj.celery_config import make_celery, get_options
from proj.config import Config
app = Flask(__name__)
app.config.from_object(Config)
celery = make_celery(app)
options = get_options(app)
worker = worker(app)
@shared_task()
def run_listener():
listen()
@app.route('/actuator/health')
def health_check():
return jsonify({'status': 'UP'})
@app.route('/')
def hello_world():
"""
A simple test route for verifying flask is working.
:return: string containing "Hello, World!"
"""
logger.info("Hello world called!")
return 'Hello, World!'
def main():
return app
make_celery 和 get_options 的代码是:
from celery import Celery
def make_celery(app):
celery = Celery(
app.import_name,
backend=app.config['CELERY_BROKER_URL'],
broker=app.config['CELERY_BROKER_URL']
)
celery.conf.update(app.config)
class ContextTask(celery.Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
def get_options(app):
return {
'broker': app.config['CELERY_BROKER_URL'],
'traceback': True,
'loglevel': 'info',
'queues': 'q1'
}
我还没有设置所有端点,但这里有一些非常重要的事情:任务 run_listener
需要在启动时工作,而无需在应用程序外运行工作程序。意思是我不能做 celery -A tasks ...
。我只希望它在运行 Flask 应用程序时运行。有没有办法做到这一点?
我尝试运行 worker.run(**options)
但我收到错误,无论我在初始化工作对象时使用 flask 应用程序还是 celery 应用程序。我错过了什么吗?