Running background Celery task in Flask

2019-04-02 13:20发布

问题:

Problem has been updated to include progress made

I have the following code and my celery tasks kick off fine, I just don't know where I should store the async result so that I can look at it again later

#!/usr/bin/env python

"""Page views."""

from flask import render_template, request
from flask import Flask

from celerytest import add

from time import sleep


app = Flask(__name__)

async_res = []

@app.route('/', methods=['GET', 'POST'])
def run():
    if request.method == 'GET':
        return render_template("template.html")
    else:
        form = request.form
        n1 = str(form.get("n1"))
        n2 = str(form.get("n2"))
        aysnc_res = add.delay(n1,n2)
        return render_template("loading.html")

@app.route('/loading')
def check_if_complete():
    if async_res.ready() == True:
        return render_template("template2.html", val=async_res.get())
    else:
        sleep(5)
        return render_template("loading.html")


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

It appears that storing async_res as a global variable in my flask app causes server errors. So what's the best method of storing the result so that I can check on it in my "loading page"

回答1:

I ended up being able to save the ID of my task in the session dictionary in Flask

See code below:

#!/usr/bin/env python

"""Page views."""

from flask import render_template, request
from flask import Flask

from celerytest import add

from time import sleep


app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def run():
    if request.method == 'GET':
        return render_template("template.html")
    else:
        form = request.form
        n1 = str(form.get("n1"))
        n2 = str(form.get("n2"))
        aysnc_res = add.delay(n1,n2)
        session['TASK_ID'] = async_res.id
        return render_template("loading.html")

@app.route('/loading')
def check_if_complete():
    aysnc_res = session['TASK_ID']
    if async_res.ready() == True:
        return render_template("template2.html", val=async_res.get())
    else:
        sleep(5)
        return render_template("loading.html")


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