python - How to execute function after returning Flask response (hosted on Heroku)? -


while i've heared need use called "job queue" i'm new , i've had hard time setting up. how execute function after returning response in flask? walk me through process?

so i've figured out that it's extremely easy , easier on heroku problem documentation quite scattered around , who's discovering job queues may overwhelming.

for example i'm going use reddis go addon on heroku first thing have install dashboard. after set flask app this:

from flask import flask rq import queue redis import redis import os import urllib.parse urlparse  app = flask(__name__)  def function_to_queue():     return "finished" # tell rq redis connection use , parse url global variable added addon redis_url = os.getenv('redistogo_url') urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) conn = redis(host=url.hostname, port=url.port, db=0, password=url.password) q = queue(connection=conn)  #no args implies default queue  @app.route('/') def hello():     ob = q.enqueue(function_to_queue) #add defined function queue     return "k?" if __name__ == '__main__':     app.run() 

next have create python script called run-worker.py code below:

import os import urllib.parse urlparse redis import redis rq import worker, queue, connection  listen = ['high', 'default', 'low']  redis_url = os.getenv('redistogo_url') if not redis_url:     raise runtimeerror('set redis go first.')  urlparse.uses_netloc.append('redis') url = urlparse.urlparse(redis_url) conn = redis(host=url.hostname, port=url.port, db=0, password=url.password)  connection(conn):     worker = worker(map(queue, listen))     worker.work() 

now modify procfile on heroku this:

web: gunicorn hello:app --log-file - worker: python -u run-worker.py 

deploy this, make sure have both worker , app started... annnd you're done. hope helps others understanding job queueing faster.


Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -