Redis 中文文档 Redis 中文文档
指南
redis.io (opens new window)
指南
redis.io (opens new window)
  • 关于
    • Redis 开源治理
    • Redis 发布周期
    • Redis 赞助商
  • 入门
  • 数据类型
  • Redis Stack
  • 命令
  • 手册

Django-RQ


Django integration with RQ, a Redis based Python queuing library. Django-RQ is a simple app that allows you to configure your queues in django's settings.py and easily use them in your project.

Support Django-RQ


If you find django-rq useful, please consider supporting its development via Tidelift.

Requirements


Django (2.0+)
RQ

Installation


Install django-rq (or download from PyPI ):

  1. ``` python
  2. pip install django-rq
  3. ```

Add django_rq to INSTALLED_APPS in settings.py :

  1. ``` python
  2. INSTALLED_APPS = (
  3.     # other apps
  4.     "django_rq",
  5. )
  6. ```

Configure your queues in django's settings.py :

  1. ``` python
  2. RQ_QUEUES = {
  3.     'default': {
  4.         'HOST': 'localhost',
  5.         'PORT': 6379,
  6.         'DB': 0,
  7.         'USERNAME': 'some-user',
  8.         'PASSWORD': 'some-password',
  9.         'DEFAULT_TIMEOUT': 360,
  10.         'REDIS_CLIENT_KWARGS': {    # Eventual additional Redis connection arguments
  11.             'ssl_cert_reqs': None,
  12.         },
  13.     },
  14.     'with-sentinel': {
  15.         'SENTINELS': [('localhost', 26736), ('localhost', 26737)],
  16.         'MASTER_NAME': 'redismaster',
  17.         'DB': 0,
  18.         # Redis username/password
  19.         'USERNAME': 'redis-user',
  20.         'PASSWORD': 'secret',
  21.         'SOCKET_TIMEOUT': 0.3,
  22.         'CONNECTION_KWARGS': {  # Eventual additional Redis connection arguments
  23.             'ssl': True
  24.         }
  25.         'SENTINEL_KWARGS': {    # Eventual Sentinel connection arguments
  26.             # If Sentinel also has auth, username/password can be passed here
  27.             'username': 'sentinel-user',
  28.             'password': 'secret',
  29.         },
  30.     },
  31.     'high': {
  32.         'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku
  33.         'DEFAULT_TIMEOUT': 500,
  34.     },
  35.     'low': {
  36.         'HOST': 'localhost',
  37.         'PORT': 6379,
  38.         'DB': 0,
  39.     }
  40. }

  41. RQ_EXCEPTION_HANDLERS = ['path.to.my.handler'] # If you need custom exception handlers
  42. ```

Include django_rq.urls in your urls.py :

  1. ``` python
  2. urlpatterns += [
  3.     path('django-rq/', include('django_rq.urls'))
  4. ]
  5. ```

Usage


Putting jobs in the queue


Django-RQ allows you to easily put jobs into any of the queues defined in settings.py. It comes with a few utility functions:

enqueue - push a job to the default queue:

  1. ``` python
  2. import django_rq
  3. django_rq.enqueue(func, foo, bar=baz)
  4. ```

get_queue - returns an Queue instance.

  1. ``` python
  2. import django_rq
  3. queue = django_rq.get_queue('high')
  4. queue.enqueue(func, foo, bar=baz)
  5. ```

In addition to name argument, get_queue also accepts default_timeout, is_async, autocommit, connection and queue_class arguments. For example:

  1. ``` python
  2. queue = django_rq.get_queue('default', autocommit=True, is_async=True, default_timeout=360)
  3. queue.enqueue(func, foo, bar=baz)
  4. ```

You can provide your own singleton Redis connection object to this function so that it will not create a new connection object for each queue definition. This will help you limit number of connections to Redis server. For example:

  1. ``` python
  2. import django_rq
  3. import redis
  4. redis_cursor = redis.StrictRedis(host='', port='', db='', password='')
  5. high_queue = django_rq.get_queue('high', connection=redis_cursor)
  6. low_queue = django_rq.get_queue('low', connection=redis_cursor)
  7. ```

get_connection - accepts a single queue name argument (defaults to "default") and returns a connection to the queue's Redis server:

  1. ``` python
  2. import django_rq
  3. redis_conn = django_rq.get_connection('high')
  4. ```

get_worker - accepts optional queue names and returns a new RQ Worker instance for specified queues (or default queue):

  1. ``` python
  2. import django_rq
  3. worker = django_rq.get_worker() # Returns a worker for "default" queue
  4. worker.work()
  5. worker = django_rq.get_worker('low', 'high') # Returns a worker for "low" and "high"
  6. ```

@job decorator


To easily turn a callable into an RQ task, you can also use the @job decorator that comes with django_rq :

  1. ``` python
  2. from django_rq import job

  3. @job
  4. def long_running_func():
  5.     pass
  6. long_running_func.delay() # Enqueue function in "default" queue

  7. @job('high')
  8. def long_running_func():
  9.     pass
  10. long_running_func.delay() # Enqueue function in "high" queue
  11. ```

You can pass in any arguments that RQ's job decorator accepts:

  1. ``` python
  2. @job('default', timeout=3600)
  3. def long_running_func():
  4.     pass
  5. long_running_func.delay() # Enqueue function with a timeout of 3600 seconds.
  6. ```

It's possible to specify default for result_ttl decorator keyword argument via DEFAULT_RESULT_TTL setting:

  1. ``` python
  2. RQ = {
  3.     'DEFAULT_RESULT_TTL': 5000,
  4. }
  5. ```

With this setting, job decorator will set result_ttl to 5000 unless it's specified explicitly.

Running workers


django_rq provides a management command that starts a worker for every queue specified as arguments:

python manage.py rqworker high default low If you want to run rqworker in burst mode, you can pass in the --burst flag:

python manage.py rqworker high default low --burst If you need to use custom worker, job or queue classes, it is best to use global settings (see Custom queue classes and Custom job and worker classes ). However, it is also possible to override such settings with command line options as follows.

To use a custom worker class, you can pass in the --worker-class flag with the path to your worker:

python manage.py rqworker high default low --worker-class 'path.to.GeventWorker' To use a custom queue class, you can pass in the --queue-class flag with the path to your queue class:

python manage.py rqworker high default low --queue-class 'path.to.CustomQueue' To use a custom job class, provide --job-class flag.

Support for scheduled jobs


With RQ 1.2.0. you can use built-in scheduler for your jobs. For example:

  1. ``` python
  2. from django_rq.queues import get_queue
  3. queue = get_queue('default')
  4. job = queue.enqueue_at(datetime(2020, 10, 10), func)
  5. ```

If you are using built-in scheduler you have to start workers with scheduler support:

python manage.py rqworker --with-scheduler Alternatively you can use RQ Scheduler. After install you can also use the get_scheduler function to return a Scheduler instance for queues defined in settings.py's RQ_QUEUES. For example:

  1. ``` python
  2. import django_rq
  3. scheduler = django_rq.get_scheduler('default')
  4. job = scheduler.enqueue_at(datetime(2020, 10, 10), func)
  5. ```

You can also use the management command rqscheduler to start the scheduler:

python manage.py rqscheduler ### Support for django-redis and django-redis-cache

If you have django-redis or django-redis-cache installed, you can instruct django_rq to use the same connection information from your Redis cache. This has two advantages: it's DRY and it takes advantage of any optimization that may be going on in your cache setup (like using connection pooling or Hiredis.)

To use configure it, use a dict with the key USE_REDIS_CACHE pointing to the name of the desired cache in your RQ_QUEUES dict. It goes without saying that the chosen cache must exist and use the Redis backend. See your respective Redis cache package docs for configuration instructions. It's also important to point out that since the django-redis-cache ShardedClient splits the cache over multiple Redis connections, it does not work.

Here is an example settings fragment for django-redis:

  1. ``` python
  2. CACHES = {
  3.     'redis-cache': {
  4.         'BACKEND': 'redis_cache.cache.RedisCache',
  5.         'LOCATION': 'localhost:6379:1',
  6.         'OPTIONS': {
  7.             'CLIENT_CLASS': 'django_redis.client.DefaultClient',
  8.             'MAX_ENTRIES': 5000,
  9.         },
  10.     },
  11. }

  12. RQ_QUEUES = {
  13.     'high': {
  14.         'USE_REDIS_CACHE': 'redis-cache',
  15.     },
  16.     'low': {
  17.         'USE_REDIS_CACHE': 'redis-cache',
  18.     },
  19. }
  20. ```

Queue Statistics


django_rq also provides a dashboard to monitor the status of your queues at /django-rq/ (or whatever URL you set in your urls.py during installation.

You can also add a link to this dashboard link in /admin by adding RQ_SHOW_ADMIN_LINK = True in settings.py. Be careful though, this will override the default admin template so it may interfere with other apps that modifies the default admin template.

These statistics are also available in JSON format via /django-rq/stats.json, which is accessible to staff members. If you need to access this view via other HTTP clients (for monitoring purposes), you can define RQ_API_TOKEN and access it via /django-rq/stats.json/<API_TOKEN>.

demo-django-rq-json-dashboard.png

Note: Statistics of scheduled jobs display jobs from RQ built-in scheduler, not optional RQ scheduler.

Additionally, these statistics are also accessible from  the command line.

  1. ``` shell
  2. python manage.py rqstats
  3. python manage.py rqstats --interval=1  # Refreshes every second
  4. python manage.py rqstats --json  # Output as JSON
  5. python manage.py rqstats --yaml  # Output as YAML
  6. ```

demo-django-rq-cli-dashboard.gif

Configuring Sentry


Django-RQ >= 2.0 uses sentry-sdk instead of the deprecated raven library. Sentry should be configured within the Django settings.py as described in the Sentry docs.

You can override the default Django Sentry configuration when running the rqworker command by passing the sentry-dsn option:

`./manage.py rqworker --sentry-dsn=https://@sentry.io/222222`

This will override any existing Django configuration and reinitialise Sentry, setting the following Sentry options:

  1. ``` python
  2. {
  3.     'debug': options.get('sentry_debug'),
  4.     'ca_certs': options.get('sentry_ca_certs'),
  5.     'integrations': [RedisIntegration(), RqIntegration(), DjangoIntegration()]
  6. }
  7. ```

Configuring Logging


RQ uses Python's logging, this means you can easily configure rqworker 's logging mechanism in django's settings.py. For example:

  1. ``` python
  2. LOGGING = {
  3.     "version": 1,
  4.     "disable_existing_loggers": False,
  5.     "formatters": {
  6.         "rq_console": {
  7.             "format": "%(asctime)s %(message)s",
  8.             "datefmt": "%H:%M:%S",
  9.         },
  10.     },
  11.     "handlers": {
  12.         "rq_console": {
  13.             "level": "DEBUG",
  14.             "class": "rq.utils.ColorizingStreamHandler",
  15.             "formatter": "rq_console",
  16.             "exclude": ["%(asctime)s"],
  17.         },
  18.         # If you use sentry for logging
  19.         'sentry': {
  20.             'level': 'ERROR',
  21.             'class': 'raven.contrib.django.handlers.SentryHandler',
  22.         },
  23.     },
  24.     'loggers': {
  25.         "rq.worker": {
  26.             "handlers": ["rq_console", "sentry"],
  27.             "level": "DEBUG"
  28.         },
  29.     }
  30. }
  31. ```

Note: error logging to Sentry is known to be unreliable with RQ when using async transports (the default transport). Please configure Raven to use sync+https:// or requests+https:// transport in settings.py :

  1. ``` python
  2. RAVEN_CONFIG = {
  3.     'dsn': 'sync+https://public:secret@example.com/1',
  4. }
  5. ```

For more info, refer to Raven's documentation.

Custom Queue Classes


By default, every queue will use DjangoRQ class. If you want to use a custom queue class, you can do so by adding a QUEUE_CLASS option on a per queue basis in RQ_QUEUES :

  1. ``` python
  2. RQ_QUEUES = {
  3.     'default': {
  4.         'HOST': 'localhost',
  5.         'PORT': 6379,
  6.         'DB': 0,
  7.         'QUEUE_CLASS': 'module.path.CustomClass',
  8.     }
  9. }
  10. ```

or you can specify DjangoRQ to use a custom class for all your queues in RQ settings:

  1. ``` python
  2. RQ = {
  3.     'QUEUE_CLASS': 'module.path.CustomClass',
  4. }
  5. ```

Custom queue classes should inherit from django_rq.queues.DjangoRQ.

If you are using more than one queue class (not recommended), be sure to only run workers on queues with same queue class. For example if you have two queues defined in RQ_QUEUES and one has custom class specified, you would have to run at least two separate workers for each queue.

Custom Job and Worker Classes


Similarly to custom queue classes, global custom job and worker classes can be configured using JOB_CLASS and WORKER_CLASS settings:

  1. ``` python
  2. RQ = {
  3.     'JOB_CLASS': 'module.path.CustomJobClass',
  4.     'WORKER_CLASS': 'module.path.CustomWorkerClass',
  5. }
  6. ```

Custom job class should inherit from rq.job.Job. It will be used for all jobs if configured.

Custom worker class should inherit from rq.worker.Worker. It will be used for running all workers unless overridden by rqworker management command worker-class option.

Testing Tip


For an easier testing process, you can run a worker synchronously this way:

  1. ``` python
  2. from django.test import TestCase
  3. from django_rq import get_worker

  4. class MyTest(TestCase):
  5.     def test_something_that_creates_jobs(self):
  6.         ...                      # Stuff that init jobs.
  7.         get_worker().work(burst=True)  # Processes all jobs then stop.
  8.         ...                      # Asserts that the job stuff is done.
  9. ```

Synchronous Mode


You can set the option ASYNC to False to make synchronous operation the default for a given queue. This will cause jobs to execute immediately and on the same thread as they are dispatched, which is useful for testing and debugging. For example, you might add the following after you queue configuration in your settings file:

  1. ``` python
  2. # ... Logic to set DEBUG and TESTING settings to True or False ...

  3. # ... Regular RQ_QUEUES setup code ...

  4. if DEBUG or TESTING:
  5.     for queueConfig in RQ_QUEUES.values():
  6.         queueConfig['ASYNC'] = False
  7. ```

Note that setting the is_async parameter explicitly when calling get_queue will override this setting.

Running Tests


To run django_rq 's test suite:

which django-admin.py test django_rq --settings=django_rq.tests.settings --pythonpath=. ## Deploying on Ubuntu

Create an rqworker service that runs the high, default, and low queues.

sudo vi /etc/systemd/system/rqworker.service

  1. ``` shell
  2. [Unit]
  3. Description=Django-RQ Worker
  4. After=network.target

  5. [Service]
  6. WorkingDirectory=<<path_to_your_project_folder>>
  7. ExecStart=/home/ubuntu/.virtualenv/<<your_virtualenv>>/bin/python \
  8.     <<path_to_your_project_folder>>/manage.py \
  9.     rqworker high default low

  10. [Install]
  11. WantedBy=multi-user.target
  12. ```

Enable and start the service

  1. ``` shell
  2. sudo systemctl enable rqworker
  3. sudo systemctl start rqworker
  4. ```

Deploying on Heroku


Add django-rq to your requirements.txt file with:

  1. ``` shell
  2. pip freeze > requirements.txt
  3. ```

Update your Procfile to:

  1. ``` shell
  2. web: gunicorn --pythonpath="$PWD/your_app_name" config.wsgi:application

  3. worker: python your_app_name/manage.py rqworker high default low
  4. ```

Commit and re-deploy. Then add your new worker with:

  1. ``` shell
  2. heroku scale worker=1
  3. ```

Changelog


See CHANGELOG.md.
Last Updated: 2023-09-03 19:17:54