烧瓶:传递背景工作者工作(rq,redis)

时间:2012-08-28 14:54:48

标签: python session redis backgroundworker flask

我想做一件非常简单的事情:启动一个工作人员,然后将答案返回给用户。 我正在尝试使用Flask和RQ的组合。

import os
from flask import Flask, session
from somewhere import do_something
from rq import Queue
from worker import conn

app = Flask(__name__)
app.debug = True
app.secret_key = '....'

q = Queue(connection=conn)

@app.route('/make/')
def make():
    job = q.enqueue(do_something, 'argument')
    session['job'] = job
    return 'Done'

@app.route('/get/')
def get():
    try:
        session['job'].refresh()
        out = str(session['job'].result)
    except:
        out = 'No result yet'
    return out

这个非常简单的例子中的想法是人们去/ make /并开始工作。经过一段时间后,可以进入/获取/并且工作人员的结果将被打印出来。

然而,一行导致问题:

session['job'] = job

似乎这项工作无法被腌制,这显然是由Flaks会议使用的。我收到了错误:

...
10:52:16 web.1     |   File "/Users/julius/twitter-sentiment/venv/lib/python2.7/site-packages/flask/app.py", line 804, in save_session
10:52:16 web.1     |     return self.session_interface.save_session(self, session, response)
10:52:16 web.1     |   File "/Users/julius/twitter-sentiment/venv/lib/python2.7/site-packages/flask/sessions.py", line 205, in save_session
10:52:16 web.1     |     secure=secure, domain=domain)
10:52:16 web.1     |   File "/Users/julius/twitter-sentiment/venv/lib/python2.7/site-packages/werkzeug/contrib/securecookie.py", line 329, in save_cookie
10:52:16 web.1     |     data = self.serialize(session_expires or expires)
10:52:16 web.1     |   File "/Users/julius/twitter-sentiment/venv/lib/python2.7/site-packages/werkzeug/contrib/securecookie.py", line 235, in serialize
10:52:16 web.1     |     self.quote(value)
10:52:16 web.1     |   File "/Users/julius/twitter-sentiment/venv/lib/python2.7/site-packages/werkzeug/contrib/securecookie.py", line 192, in quote
10:52:16 web.1     |     value = cls.serialization_method.dumps(value)
10:52:16 web.1     |   File "/Users/julius/twitter-sentiment/venv/bin/../lib/python2.7/copy_reg.py", line 70, in _reduce_ex
10:52:16 web.1     |     raise TypeError, "can't pickle %s objects" % base.__name__
10:52:16 web.1     | TypeError: can't pickle function objects

我真的希望有所帮助。我可能会以完全错误的方式(通过会话传递作业)这样做,但我不知道如何访问作业的结果......

任何帮助都将受到高度赞赏。

提前致谢。

2 个答案:

答案 0 :(得分:3)

之前我没有使用rq,但我发现某个作业有.key属性。在会话中存储该哈希可能更容易。然后,您可以使用Job类的.fetch方法,该方法本身会调用.refresh()并将作业返回给您。在那时阅读.result()将为您提供工作的当前状态。

也许这样(未经测试):

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

答案 1 :(得分:2)

序列化参数的问题(实际上你试图序列化pickle不可能的函数对象。)

尝试

@app.route('/make/')
def make():
    job = q.enqueue(func=do_something, args=('argument',))
    session['job'] = job
    return 'Done'