I've a application using Flask and Celery. Right now I have a endpoint called "/get-products", but I want it to be schedule when I call it.
What I want is call that endpoint, and it schelude itself, without trigge other function or anything
Is there a way to do that?
CodePudding user response:
This is the general idea:
Create a function that will do the actual processing in a function named, for example, get_products_task
and decorate it with @celery_task
. Then your endpoint function for /get-products will determine how many seconds in the future it wishes to run the the celery task and schedule it accordingly. For example:
@celery_task
get_products_task():
with app.app_context(): # if an application context is required
...
@app.route('/get-products')
def get_products():
task = get_products_task.apply_async(countdown=120)
return render_template('schedule_get_products_template.html'), 202
#return '/get-products has been scheduled!', 202
If the /get_products endpoint is to be called sometimes without delay, then its logic really should be factored out into a separate function, for example,get_products_logic
:
def get_products_logic():
"""
The actual logic for getting products.
The assumption is that an application context exists, if necessary.
"""
...
@celery_task
def get_products_task():
with app.app_context(): # if an application context is required
get_products_logic()
@app.route('/get-products')
def get_products():
get_products_logic()
return reneder_template('get_products_template.html'), 200
@app.route('/schedule-get-products')
def schedule_get_products():
task = get_products_task.apply_async(countdown=120)
return render_template('schedule_get_products_template.html'), 202
#return '/get-products has been scheduled!', 202