Flask: passing around background worker job (rq, redis)

后端 未结 2 1812
后悔当初
后悔当初 2021-02-06 07:06

I want to do a very simple thing: Launch a worker to something and then return the answer to user. I\'m trying to do so using a combination of Flask and RQ.

impo         


        
2条回答
  •  清酒与你
    2021-02-06 07:44

    I've not used rq before but I see that a job has a .key property. It might be easier to store that hash in your session. Then you can use the Job class's .fetch method which will itself call a .refresh() and return the job to you. Reading the .result() at that point would give you the job's current status.

    Maybe like this (untested):

    from rq.job import Job
    
    @app.route('/make/')
    def make():
        job = q.enqueue(do_something, 'argument')
        session['job'] = job.key
        return 'Done'
    
    @app.route('/get/')
    def get():
        try:
            job = Job()
            job.fetch(session['job'])
            out = str(job.result)
        except:
            out = 'No result yet'
        return out
    

提交回复
热议问题