How to execute a function after returning a flask response (hosted on Heroku)?

So far I've heard I need to use something called a "job queue". I'm new to this and had a hard time getting it all set up. How to execute a function after returning a response in a flash? Can you walk through the process?

+3


source to share


1 answer


So I realized that it is very easy to do and even easier on the hero, the problem is that the documentation is quite scattered and for those just discovering the job queues it can be overwhelming.

For this example, I'm going to use the Reddis To Go addon on Heroku , so the first thing you need to do is install it from your panel. ... After that, you set up your application for flash drives also looks like this:

from flask import Flask
from rq import Queue
from redis import Redis
import os
import urllib.parse as urlparse

app = Flask(__name__)

def function_to_queue():
    return "finished"
# Tell RQ what Redis connection to use and parse url from the global variable that was added by the 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 the default queue

@app.route('/')
def hello():
    ob = q.enqueue(function_to_queue) #Add previously defined function to queue
    return "k?"
if __name__ == '__main__':
    app.run()

      

Then you need to create a python script called run-worker.py

with the code below:



import os
import urllib.parse as urlparse
from redis import Redis
from rq import Worker, Queue, Connection

listen = ['high', 'default', 'low']

redis_url = os.getenv('REDISTOGO_URL')
if not redis_url:
    raise RuntimeError('Set up Redis To 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)

with Connection(conn):
    worker = Worker(map(Queue, listen))
    worker.work()

      

Now just change your Procfile to heroku to look like this:

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

      

Expand this, make sure you already have a worker and an application ... annnd you done. Hopefully this will help others understand how queuing works faster.

+3


source







All Articles