0

I have a question for example I've created a Python flask app and everything works well, but here's a thing one of the functions take around a minute to two minutes to complete.

Is there a way to make user not wait 1 - 2 minutes for a function to complete? for example user would use app normally on front end, make request to backend API and use the rest of the app while that request is completed? has anyone done anything similar and are there libraries for such cases when there are long requests? or is that due to how my functions are structured?

  • 2 min quite a long time, but again it depends on the process/program importance you are using – sahasrara62 Jun 22 '20 at 09:56
  • I agree it is quite long time it's an unusual app, but what do you mean by process importance? Let's say process can't really be sliced into multiple smaller parts if that's what you mean – jalope4221 Jun 22 '20 at 09:57
  • yeah it depend on how the process is working, for example if you deploying code on server and expect 1-2 min in your application front end then it is quite not possible so it will take time and can't be made in chunks and you need to wait for fully deploy or you can explore/work on different part of that application – sahasrara62 Jun 22 '20 at 10:01
  • There are several similar questions on this site ([How to execute long requests](https://stackoverflow.com/q/14904523/6682517), [python flask - run script after processing the request](https://stackoverflow.com/q/38894551/6682517)). The answers are not very detailed by the Stackoverflow standards but they suggest some vital solutions. In brief: you need to use a scheduler library like [Celery](https://docs.celeryproject.org/en/stable/getting-started/introduction.html) of [Flask-APScheduler](https://github.com/viniciuschiele/flask-apscheduler). – Sergey Shubin Jun 22 '20 at 10:46

1 Answers1

0

I've already implemented REST api similar this.

I used celery library and redis as broker and backed.

Request API is like below and func is celery task.

def your_api():
    ...
    async_task = func.delay(your_params)
    return async_task.task_id

and you should inquiry by your task_id like below:

def inquiry_result():
    task_id = ... # get from client
    res = celery.AsyncResult(task_id)
    if res.ready(): # if result is ready
        return res.get() # you can get result
    return None

celery task sample code:

@celery_app.task
def func(...):
    # do some thing
    result = ...
    return result
ahmadgh74
  • 801
  • 6
  • 10