将芹菜与flask_restful一起使用

时间:2019-09-27 14:13:57

标签: python api celery flask-restful

我有一个简单的Flask Restful API,由于某些端点需要大量的执行时间,因此我想将请求作为Celery任务执行。

main.py:

from flask import Flask
from flask_restful import Api
from flask_celery import make_celery

app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0',
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'

celery = make_celery(app)
api = Api(app)

api.add_resource(someResource, '/someendpoint/')

if __name__ == '__main__':
    app.run(debug=True)

与make_celery.py:

from celery import Celery

def make_celery(app):
    celery = Celery(
        app.import_name,
        backend=app.config['CELERY_RESULT_BACKEND'],
        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

我现在想定义我在resource.py中定义的资源是一个芹菜任务:

class Cost(Resource):

    def get(self):

        result = some_code 

        return result

在这里使get方法成为芹菜任务的最方便的方法是什么?

非常感谢!

0 个答案:

没有答案