Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to get job result by RQ

Tags:

python

I have code like this:

from rq import Queue, use_connection
from task import add
from redis import Redis
import time
import logging

# use redis by default
# create work queue
redis_conn = Redis()
q = Queue(connection=redis_conn) 

#notice: cann't run a task function in __main__ module
#because rq save module and function name in redis
#when rqworker running, __main__ is another module
# enqueue tasks,function enqueue returns the job instance
job = q.enqueue(add, 3, 9)
job = q.enqueue(add, 4, 9)
job = q.enqueue(add, 5, 9)
job = q.enqueue(add, 6, 9)

time.sleep(3)
#get the job result by job.result
logging.warn("result is %s", job.result)

When I run the application I get output like this:

WARNING:root:result is 15

 

How can I get the previous result??

like image 577
anhlt Avatar asked Apr 01 '14 04:04

anhlt


1 Answers

I just figure out solution.

def recommend(request):
    user_id = int(request.GET.get('user_id','287'))
    job = django_rq.enqueue(recommended,user_id) # Enqueue Job
    logger.debug(job.key)
    response_data = {'status':'processing', 'job': job.key}
    return HttpResponse(json.dumps(response_data), content_type="application/json")

def get_result(request):
    job_id = request.GET.get('job_id')
    redis_conn = django_rq.get_connection()
    job_id=job_id.split(':')[2] 
    logger.info(job_id)
    job = Job.fetch(job_id,redis_conn) #fetch Job from redis
    if job.is_finished:
        ret = job.return_value
    elif job.is_queued:
        ret = {'status':'in-queue'}
    elif job.is_started:
        ret = {'status':'waiting'}
    elif job.is_failed:
        ret = {'status': 'failed'}
    return HttpResponse(json.dumps(ret), content_type="application/json")

Here is some code from my Django project using django_rq library. Just remember Job.key look like this "job:id:job_key". Split by : and get the second element

like image 164
anhlt Avatar answered Oct 17 '22 18:10

anhlt