Flask芹菜应用程序与普通Flask应用程序(如何使它们同时协同工作)

时间:2017-02-10 20:06:17

标签: python flask celery

我有一个Flask Celery应用程序,用于实例化celery实例。 我理解,从.py文件的角度来看,我可以将一个普通的Flask路由添加到同一个.py文件中,我需要运行两次相同的代码:

  1. 运行worker:

    %芹菜工人-A app.celery ...

  2. 运行与普通Flask app相同的代码:

    %python app.py ...

  3. 我的问题是:如果正常的Flask应用程序是与Celery应用程序真正独立的进程,那么我怎样才能从Flask路由操作正在运行的芹菜实例来执行以下操作:

      celery.control.purge()
      celery.control.inspect() etc ???
    

    这是我的代码:

    import os
    import random
    import time
    from flask import Flask, request, render_template, session, flash, redirect, \
        url_for, jsonify
    from celery import Celery
    
    app = Flask(__name__)
    
    # Celery configuration
    app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
    app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'
    
    # Initialize Celery
    celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    
    
    @celery.task
    def send_async_email(msg):
        """Background task to send an email with Flask-Mail."""
        with app.app_context():
            mail.send(msg)
    
    
    @app.route('/purge', methods=['GET', 'POST'])
    def purge_tasks():
        ## want to do stuffs with the running celery instance, e.g:
        ## doing:
        ##    celery.control.purge()
        ##    celery.control.inspect()
        ##
        ## BUT HOW??
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    我一直在网上寻找答案,但没有一个答案专门回答了这个问题。

    非常感谢您的任何帮助/指针。

1 个答案:

答案 0 :(得分:0)

这个http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#application看起来会回答你的问题。阅读应用程序,然后调用任务。您需要做的是将Flask应用程序保存为"任务"如文档中所述,然后将该任务传递给Celery实例,顺便称为" app"太