如何在后台任务中访问redis连接
How to access redis connection in background task
我正在尝试扩展 flask-base 项目 https://github.com/hack4impact/flask-base/tree/master/app which comes with a user model only. I'm trying to add the ability to run a background task on redis using rq. I've found 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
但我得到:
语法错误:语法无效。
如何在后台任务中访问 conn 变量?
您可以尝试进行以下更改:
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)
我联系了提供以下信息的开发者:
我正在尝试扩展 flask-base 项目 https://github.com/hack4impact/flask-base/tree/master/app which comes with a user model only. I'm trying to add the ability to run a background task on redis using rq. I've found 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
但我得到:
语法错误:语法无效。
如何在后台任务中访问 conn 变量?
您可以尝试进行以下更改:
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)
我联系了提供以下信息的开发者: