如何在后台任务中访问redis连接

时间:2018-02-12 15:59:09

标签: python flask redis python-rq

enter image description here

我试图扩展只有用户模型附带的基于烧瓶的项目https://github.com/hack4impact/flask-base/tree/master/app。我尝试使用rq添加在redis上运行后台任务的功能。我发现https://devcenter.heroku.com/articles/python-rq很有帮助。

此应用程序支持redis队列,后台redis队列通过运行实现:

@manager.command
def run_worker():
    """Initializes a slim rq task queue."""
    listen = ['default']
    conn = Redis(
        host=app.config['RQ_DEFAULT_HOST'],
        port=app.config['RQ_DEFAULT_PORT'],
        db=0,
        password=app.config['RQ_DEFAULT_PASSWORD'])

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

使用:

$ python manage.py run_worker

在我看来,我有:

@main.route('/selected')
def background_selected():
    from rq import Queue
    from manage import run_worker.conn
    q = Queue(connection=conn)
    return q.enqueue(selected)

问题是我不知道如何将run_worker()中创建的连接导入到我的视图中。我尝试过各种变体:

from manage import run_worker.conn

但我得到了:

SyntaxError:语法无效。

如何在后台任务中访问conn变量?

1 个答案:

答案 0 :(得分:1)

来自文档python-rq Configuration

您可以尝试进行以下更改:

<强> manager.py

import redis

"""Initializes a slim rq task queue."""
listen = ['default']
conn = redis.Redis(host=app.config['RQ_DEFAULT_HOST'], 
                   port=app.config['RQ_DEFAULT_PORT'],
                   db=0,     
                   password=app.config['RQ_DEFAULT_PASSWORD'])

@manager.command
def run_worker():
    with Connection(conn):
        worker = Worker(map(Queue, listen))
        worker.work()

并从视图:

from rq import Queue
from manage import conn

q = Queue(connection=conn)
相关问题