Noppanit

08 Mar 2013

# Flask and RQ example for Heroku

I have been struggling to find any example on the Internet on how to do long polling on Heroku with Flask and RQ. I know it’s relatively easy, but I just want to make it clear for my future self.

It’s really simple.

@app.route('/get_word_count', methods=['POST'])
def get_word_count():
data_json = json.loads(request.data)
job = q.enqueue(word_counter.count_words, data_json["sentence"])
return job.key

@app.route("/get_word_count_result/<job_key>", methods=['GET'])
def get_word_count_result(job_key):
job_key = job_key.replace("rq:job:", "")
job = Job.fetch(job_key, connection=conn)

if(not job.is_finished):
return "Not yet", 202
else:
return str(job.result), 200


The key is here

job = Job.fetch(job_key, connection=conn)


The fetch command is used to get the job by job_id, you can also use

get_current_job()


as well, but I just want to make it clear that if there are more concurrent requests coming in, I’ll get the right result back.

I posted an example here. https://github.com/noppanit/heroku-flask-rq-worker

Til next time,
noppanit at 00:00