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

问题描述 投票:0回答:2

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变量?

python flask redis python-rq
2个回答
1
投票

来自文档,python-rq Configuration

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

manager.朋友

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)

1
投票

我联系了提供以下内容的开发人员:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.