Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

python - Flask long routines

I have to do some long work in my Flask app. And I want to do it async. Just start working, and then check status from javascript.

I'm trying to do something like:

@app.route('/sync')
def sync():
    p = Process(target=routine, args=('abc',))
    p.start()

    return "Working..."

But this it creates defunct gunicorn workers.

How can it be solved? Should I use something like Celery?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are many options. You can develop your own solution, use Celery or Twisted (I'm sure there are more already-made options out there but those are the most common ones).

Developing your in-house solution isn't difficult. You can use the multiprocessing module of the Python standard library:

  • When a task arrives you insert a row in your database with the task id and status.
  • Then launch a process to perform the work which updates the row status at finish.
  • You can have a view to check if the task is finished, which actually just checks the status in the corresponding.

Of course you have to think where you want to store the result of the computation and what happens with errors.

Going with Celery is also easy. It would look like the following. To define a function to be executed asynchronously:

@celery.task
def mytask(data):

    ... do a lot of work ...

Then instead of calling the task directly, like mytask(data), which would execute it straight away, use the delay method:

result = mytask.delay(mydata)

Finally, you can check if the result is available or not with ready:

result.ready()

However, remember that to use Celery you have to run an external worker process.

I haven't ever taken a look to Twisted so I cannot tell you if it more or less complex than this (but it should be fine to do what you want to do too).

In any case, any of those solutions should work fine with Flask. To check the result it doesn't matter at all if you use Javascript. Just make the view that checks the status return JSON (you can use Flask's jsonify).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...