Debian Codegraph @

README.md

raw
1 # Django-RQ
2
3 [![Build Status](https://github.com/rq/django-rq/actions/workflows/test.yml/badge.svg)](https://github.com/rq/django-rq/actions/workflows/test.yml)
4
5 Django integration with [RQ](https://github.com/nvie/rq), a [Redis](http://redis.io/) based Python queuing library. [Django-RQ](https://github.com/rq/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.
6
7 ## Support Django-RQ
8
9 If you find `django-rq` useful, please consider supporting its development via [Tidelift](https://tidelift.com/subscription/pkg/pypi-django_rq?utm_source=pypi-django-rq&utm_medium=referral&utm_campaign=readme).
10
11 ## Requirements
12
13 - [Django](https://www.djangoproject.com/) (4.2+)
14 - [RQ](https://github.com/nvie/rq)
15
16 ## Installation
17
18 - Install `django-rq` (or [download from PyPI](http://pypi.python.org/pypi/django-rq)):
19
20 ```bash
21 pip install django-rq
22 ```
23
24 - Add `django_rq` to `INSTALLED_APPS` in `settings.py`:
25
26 ```python
27 INSTALLED_APPS = (
28 # other apps
29 "django_rq",
30 )
31 ```
32
33 - Configure your queues in Django's `settings.py`:
34
35 ```python
36 RQ_QUEUES = {
37 'default': {
38 'HOST': 'localhost',
39 'PORT': 6379,
40 'DB': 0,
41 'USERNAME': 'some-user',
42 'PASSWORD': 'some-password',
43 'DEFAULT_TIMEOUT': 360,
44 'DEFAULT_RESULT_TTL': 800,
45 'REDIS_CLIENT_KWARGS': { # Eventual additional Redis connection arguments
46 'ssl_cert_reqs': None,
47 },
48 },
49 'with-sentinel': {
50 'SENTINELS': [('localhost', 26736), ('localhost', 26737)],
51 'MASTER_NAME': 'redismaster',
52 'DB': 0,
53 # Redis username/password
54 'USERNAME': 'redis-user',
55 'PASSWORD': 'secret',
56 'SOCKET_TIMEOUT': 0.3,
57 'CONNECTION_KWARGS': { # Eventual additional Redis connection arguments
58 'ssl': True
59 },
60 'SENTINEL_KWARGS': { # Eventual Sentinel connection arguments
61 # If Sentinel also has auth, username/password can be passed here
62 'username': 'sentinel-user',
63 'password': 'secret',
64 },
65 },
66 'high': {
67 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku
68 'DEFAULT_TIMEOUT': 500,
69 },
70 'low': {
71 'HOST': 'localhost',
72 'PORT': 6379,
73 'DB': 0,
74 }
75 }
76
77 RQ_EXCEPTION_HANDLERS = ['path.to.my.handler'] # If you need custom exception handlers
78 ```
79
80 ## Admin Integration
81
82 _New in Version 4.0_
83
84 Django-RQ automatically integrates with Django's admin interface. Once installed, navigate to `/admin/django_rq/dashboard/` to access:
85 - Queue statistics and monitoring dashboard
86 - Job registry browsers (scheduled, started, finished, failed, deferred)
87 - Worker management
88 - Prometheus metrics endpoint (if `prometheus_client` is installed)
89
90 The views are automatically registered in Django admin and a link to the dashboard is added to the admin interface's sidebar. If you want to disable this link, add `RQ_SHOW_ADMIN_LINK = False` in `settings.py`.
91
92 ### Standalone URLs (Alternative)
93
94 For advanced use cases, you can also include Django-RQ views at a custom URL prefix:
95
96 ```python
97 # urls.py
98 urlpatterns += [
99 path('django-rq/', include('django_rq.urls'))
100 ]
101 ```
102
103 This makes views accessible at `/django-rq/` instead of within the admin interface at `/admin/django_rq/dashboard/`.
104
105 ### Template URL Resolution
106
107 Templates in django-rq use a custom `{% rq_url %}` tag to resolve view names inside either the admin integration or standalone URLs. The tag detects the current admin namespace (when present) and falls back to the `django_rq:` namespace, avoiding hard-coded prefixes and keeping links working in both modes.
108
109 If you copy or override django-rq templates, load the tag library and use `rq_url` instead of `url` for django-rq views:
110
111 ```django
112 {% load django_rq %}
113 <a href="{% rq_url 'home' %}">Django RQ</a>
114 ```
115
116 ## Usage
117
118 ### Putting jobs in the queue
119
120 Django-RQ allows you to easily put jobs into any of the queues defined in `settings.py`. It comes with a few utility functions:
121
122 - `enqueue` - push a job to the `default` queue:
123
124 ```python
125 import django_rq
126 django_rq.enqueue(func, foo, bar=baz)
127 ```
128
129 - `get_queue` - returns a `Queue` instance.
130
131 ```python
132 import django_rq
133 queue = django_rq.get_queue('high')
134 queue.enqueue(func, foo, bar=baz)
135 ```
136
137 In addition to `name` argument, `get_queue` also accepts `default_timeout`, `is_async`, `commit_mode`, `connection` and `queue_class` arguments. For example:
138
139 ```python
140 queue = django_rq.get_queue('default', commit_mode='on_db_commit', is_async=True, default_timeout=360)
141 queue.enqueue(func, foo, bar=baz)
142 ```
143
144 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:
145
146 ```python
147 import django_rq
148 import redis
149
150 redis_cursor = redis.StrictRedis(host='', port='', db='', password='')
151 high_queue = django_rq.get_queue('high', connection=redis_cursor)
152 low_queue = django_rq.get_queue('low', connection=redis_cursor)
153 ```
154
155 - `get_connection` - accepts a single queue name argument (defaults to "default") and returns a connection to the queue's Redis server:
156
157 ```python
158 import django_rq
159
160 redis_conn = django_rq.get_connection('high')
161 ```
162
163 - `get_worker` - accepts optional queue names and returns a new RQ `Worker` instance for specified queues (or `default` queue):
164
165 ```python
166 import django_rq
167
168 worker = django_rq.get_worker() # Returns a worker for "default" queue
169 worker.work()
170 worker = django_rq.get_worker('low', 'high') # Returns a worker for "low" and "high"
171 ```
172
173 ### `@job` decorator
174
175 To easily turn a callable into an RQ task, you can also use the `@job` decorator that comes with `django_rq`:
176
177 ```python
178 from django_rq import job
179
180 @job
181 def long_running_func():
182 pass
183
184 long_running_func.delay() # Enqueue function in "default" queue
185
186 @job('high')
187 def long_running_func():
188 pass
189
190 long_running_func.delay() # Enqueue function in "high" queue
191 ```
192
193 You can pass in any arguments that RQ's job decorator accepts:
194
195 ```python
196 @job('default', timeout=3600)
197 def long_running_func():
198 pass
199
200 long_running_func.delay() # Enqueue function with a timeout of 3600 seconds.
201 ```
202
203 It's possible to specify default for `result_ttl` decorator keyword argument via `DEFAULT_RESULT_TTL` setting:
204
205 ```python
206 RQ = {
207 'DEFAULT_RESULT_TTL': 5000,
208 }
209 ```
210
211 With this setting, job decorator will set `result_ttl` to 5000 unless it's specified explicitly or included in the queue config.
212
213 ### Running workers
214
215 django_rq provides a management command that starts a worker for every queue specified as arguments:
216
217 ```bash
218 python manage.py rqworker high default low
219 ```
220
221 If you want to run `rqworker` in burst mode, you can pass in the `--burst` flag:
222
223 ```bash
224 python manage.py rqworker high default low --burst
225 ```
226
227 If you need to use custom worker, job or queue classes, it is best to use global settings (see [Custom queue classes](#custom-queue-classes) and [Custom job and worker classes](#custom-job-and-worker-classes)). However, it is also possible to override such settings with command line options as follows.
228
229 To use a custom worker class, you can pass in the `--worker-class` flag with the path to your worker:
230
231 ```bash
232 python manage.py rqworker high default low --worker-class 'path.to.GeventWorker'
233 ```
234
235 To use a custom queue class, you can pass in the `--queue-class` flag with the path to your queue class:
236
237 ```bash
238 python manage.py rqworker high default low --queue-class 'path.to.CustomQueue'
239 ```
240
241 To use a custom job class, provide the `--job-class` flag.
242
243 Starting from version 2.10, running RQ's worker-pool is also supported:
244
245 ```bash
246 python manage.py rqworker-pool default low medium --num-workers 4
247 ```
248
249 ### Support for Scheduled Jobs
250
251 With RQ 1.2.0 you can use the [built-in scheduler](https://python-rq.org/docs/scheduling/) for your jobs. For example:
252
253 ```python
254 from datetime import datetime
255 from django_rq.queues import get_queue
256
257 queue = get_queue('default')
258 job = queue.enqueue_at(datetime(2020, 10, 10), func)
259 ```
260
261 If you are using built-in scheduler you have to start workers with scheduler support:
262
263 ```bash
264 python manage.py rqworker --with-scheduler
265 ```
266
267 ### Support for RQ's CronScheduler
268
269 Create a cron configuration file:
270
271 ```python
272 # cron_config.py
273 from rq import cron
274 from myapp.tasks import send_report, sync_data
275
276 cron.register(send_report, queue_name='default', cron='0 9 * * *') # Daily at 9:00 AM
277 cron.register(sync_data, queue_name='high', interval=30) # Every 30 seconds
278 ```
279
280 Then start the cron scheduler:
281
282 ```bash
283 python manage.py rqcron cron_config.py
284 ```
285
286 For more options, visit [RQ's CronScheduler documentation](https://python-rq.org/docs/cron/).
287
288 ### Support for django-redis and django-redis-cache
289
290 If you have [django-redis](https://django-redis.readthedocs.org/) or [django-redis-cache](https://github.com/sebleier/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](https://github.com/redis/hiredis)).
291
292 To 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.
293
294 Here is an example settings fragment for `django-redis`:
295
296 ```python
297 CACHES = {
298 'redis-cache': {
299 'BACKEND': 'redis_cache.cache.RedisCache',
300 'LOCATION': 'localhost:6379:1',
301 'OPTIONS': {
302 'CLIENT_CLASS': 'django_redis.client.DefaultClient',
303 'MAX_ENTRIES': 5000,
304 },
305 },
306 }
307
308 RQ_QUEUES = {
309 'high': {
310 'USE_REDIS_CACHE': 'redis-cache',
311 },
312 'low': {
313 'USE_REDIS_CACHE': 'redis-cache',
314 },
315 }
316 ```
317
318 ### Suspending and Resuming Workers
319
320 Sometimes you may want to suspend RQ to prevent it from processing new jobs. A classic example is during the initial phase of a deployment script or in advance of putting your site into maintenance mode. This is particularly helpful when you have jobs that are relatively long-running and might otherwise be forcibly killed during the deploy.
321
322 The `suspend` command stops workers on _all_ queues (in a single Redis database) from picking up new jobs. However currently running jobs will continue until completion.
323
324 ```bash
325 # Suspend indefinitely
326 python manage.py rqsuspend
327
328 # Suspend for a specific duration (in seconds) then automatically
329 # resume work again.
330 python manage.py rqsuspend -d 600
331
332 # Resume work again.
333 python manage.py rqresume
334 ```
335
336 ### Queue Statistics
337
338 _Changed in Version 3.0_
339
340 Various queue statistics are also available in JSON format via `/django-rq/stats.json`, which is accessible via a bearer token authentication scheme (defined in `settings.py` as `RQ_API_TOKEN`). Then, include the token in the Authorization header as a Bearer token: `Authorization: Bearer <token>` and access it via `/django-rq/stats.json`.
341
342 ![Django RQ JSON dashboard](demo-django-rq-json-dashboard.png)
343
344 Note: Statistics of scheduled jobs display jobs from [RQ built-in scheduler](https://python-rq.org/docs/scheduling/), not optional [RQ scheduler](https://github.com/rq/rq-scheduler).
345
346 Additionally, these statistics are also accessible from the command line.
347
348 ```bash
349 python manage.py rqstats
350 python manage.py rqstats --interval=1 # Refreshes every second
351 python manage.py rqstats --json # Output as JSON
352 python manage.py rqstats --yaml # Output as YAML
353 ```
354
355 ![Django RQ CLI dashboard](demo-django-rq-cli-dashboard.gif)
356
357 ### Configuring Prometheus
358
359 `django_rq` also provides a Prometheus compatible view, which can be enabled by installing `prometheus_client` or installing the extra "prometheus-metrics" (`pip install django-rq[prometheus]`). The metrics are exposed at `/django-rq/metrics/` and the following is an example of the metrics that are exported:
360
361 ```text
362 # HELP rq_workers RQ workers
363 # TYPE rq_workers gauge
364 # HELP rq_job_successful_total RQ successful job count
365 # TYPE rq_job_successful_total counter
366 # HELP rq_job_failed_total RQ failed job count
367 # TYPE rq_job_failed_total counter
368 # HELP rq_working_seconds_total RQ total working time
369 # TYPE rq_working_seconds_total counter
370 # HELP rq_jobs RQ jobs by status
371 # TYPE rq_jobs gauge
372 rq_jobs{queue="default",status="queued"} 0.0
373 rq_jobs{queue="default",status="started"} 0.0
374 rq_jobs{queue="default",status="finished"} 0.0
375 rq_jobs{queue="default",status="failed"} 0.0
376 rq_jobs{queue="default",status="deferred"} 0.0
377 rq_jobs{queue="default",status="scheduled"} 0.0
378 ```
379
380 If you need to access this view via other HTTP clients (for monitoring purposes), you can define `RQ_API_TOKEN`. Then, include the token in the Authorization header as a Bearer token: `Authorization: Bearer <token>` and access it via `/django-rq/metrics`.
381
382
383 ### Configuring Logging
384
385 RQ uses Python's `logging`, this means you can easily configure `rqworker`'s logging mechanism in Django's `settings.py`. For example:
386
387 ```python
388 LOGGING = {
389 "version": 1,
390 "disable_existing_loggers": False,
391 "formatters": {
392 "rq_console": {
393 "format": "%(asctime)s %(message)s",
394 "datefmt": "%H:%M:%S",
395 },
396 },
397 "handlers": {
398 "rq_console": {
399 "level": "DEBUG",
400 "class": "rq.logutils.ColorizingStreamHandler",
401 "formatter": "rq_console",
402 "exclude": ["%(asctime)s"],
403 },
404 },
405 'loggers': {
406 "rq.worker": {
407 "handlers": ["rq_console", "sentry"],
408 "level": "DEBUG"
409 },
410 }
411 }
412 ```
413
414 ### Custom Queue Classes
415
416 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`:
417
418 ```python
419 RQ_QUEUES = {
420 'default': {
421 'HOST': 'localhost',
422 'PORT': 6379,
423 'DB': 0,
424 'QUEUE_CLASS': 'module.path.CustomClass',
425 }
426 }
427 ```
428
429 Or you can specify `DjangoRQ` to use a custom class for all your queues in `RQ` settings:
430
431 ```python
432 RQ = {
433 'QUEUE_CLASS': 'module.path.CustomClass',
434 }
435 ```
436
437 Custom queue classes should inherit from `django_rq.queues.DjangoRQ`.
438
439 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.
440
441 ### Custom Job and Worker Classes
442
443 Similarly to custom queue classes, global custom job and worker classes can be configured using `JOB_CLASS` and `WORKER_CLASS` settings:
444
445 ```python
446 RQ = {
447 'JOB_CLASS': 'module.path.CustomJobClass',
448 'WORKER_CLASS': 'module.path.CustomWorkerClass',
449 }
450 ```
451
452 Custom job class should inherit from `rq.job.Job`. It will be used for all jobs if configured.
453
454 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.
455
456 ### Testing Tip
457
458 For an easier testing process, you can run a worker synchronously this way:
459
460 ```python
461 from django.test import TestCase
462 from django_rq import get_worker
463
464 class MyTest(TestCase):
465 def test_something_that_creates_jobs(self):
466 ... # Stuff that init jobs.
467 get_worker().work(burst=True) # Processes all jobs then stop.
468 ... # Asserts that the job stuff is done.
469 ```
470
471 ### Synchronous Mode
472
473 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 your queue configuration in your settings file:
474
475 ```python
476 # ... Logic to set DEBUG and TESTING settings to True or False ...
477
478 # ... Regular RQ_QUEUES setup code ...
479
480 if DEBUG or TESTING:
481 for queue_config in RQ_QUEUES.values():
482 queue_config['ASYNC'] = False
483 ```
484
485 Note that setting the `is_async` parameter explicitly when calling `get_queue` will override this setting.
486
487 ### Commit Modes
488
489 _New in Version 4.0_
490
491 By default, jobs are enqueued when the database transaction commits. This behavior is controlled by the `COMMIT_MODE` setting:
492
493 ```python
494 RQ = {
495 'COMMIT_MODE': 'on_db_commit', # or 'auto', 'request_finished'
496 }
497 ```
498
499 Available commit modes:
500
501 | Mode | Behavior |
502 |------|----------|
503 | `on_db_commit` (default) | Jobs are enqueued when the current database transaction commits. If not in a transaction, jobs are enqueued immediately |
504 | `auto` | Jobs are enqueued immediately when `enqueue()` is called |
505 | `request_finished` | Jobs are enqueued when Django's `request_finished` signal fires. Jobs are discarded if an exception occurs during the request |
506
507 The `on_db_commit` mode is recommended when your jobs depend on database state, as it ensures the job won't run until the data it depends on has been committed. This prevents race conditions where a job tries to access data that hasn't been committed.
508
509 ```python
510 from django.db import transaction
511
512 # With COMMIT_MODE='on_db_commit'
513 with transaction.atomic():
514 user = User.objects.create(username='new_user')
515 queue.enqueue(send_welcome_email, user.id) # Job not enqueued yet, it waits for DB transaction to commit
516
517 # Transaction committed - now the job is enqueued
518 ```
519
520 You can also explicitly set `commit_mode` when calling `get_queue()`:
521
522 ```python
523 queue = django_rq.get_queue('default', commit_mode='auto')
524 ```
525
526 **Note:** The `AUTOCOMMIT` setting is deprecated as of version 3.0. Use `COMMIT_MODE` instead:
527 - `AUTOCOMMIT: True` → `COMMIT_MODE: 'auto'`
528 - `AUTOCOMMIT: False` → `COMMIT_MODE: 'request_finished'`
529
530 **Migrating from version 2.x:** The default behavior has changed in version 3.0. Previously, jobs were enqueued immediately (`auto` mode). Now, jobs are enqueued when the database transaction commits (`on_db_commit` mode). To restore the old behavior, set `COMMIT_MODE: 'auto'` in your `RQ` settings.
531
532 ## Running Tests
533
534 To run `django_rq`'s test suite (you'll need `pytest-django`):
535
536 ```bash
537 pytest
538 ```
539
540 ## Deploying on Ubuntu
541
542 Create an rqworker service that runs the high, default, and low queues.
543
544 ```bash
545 sudo vi /etc/systemd/system/rqworker.service
546 ```
547
548 ```bash
549 [Unit]
550 Description=Django-RQ Worker
551 After=network.target
552
553 [Service]
554 WorkingDirectory=<<path_to_your_project_folder>>
555 ExecStart=/home/ubuntu/.virtualenv/<<your_virtualenv>>/bin/python \
556 <<path_to_your_project_folder>>/manage.py \
557 rqworker high default low
558
559 [Install]
560 WantedBy=multi-user.target
561 ```
562
563 Enable and start the service:
564
565 ```bash
566 sudo systemctl enable rqworker
567 sudo systemctl start rqworker
568 ```
569
570 ## Deploying on Heroku
571
572 Add `django-rq` to your `requirements.txt` file with:
573
574 ```bash
575 pip freeze > requirements.txt
576 ```
577
578 Update your `Procfile` to:
579
580 ```bash
581 web: gunicorn --pythonpath="$PWD/your_app_name" config.wsgi:application
582
583 worker: python your_app_name/manage.py rqworker high default low
584 ```
585
586 Commit and re-deploy. Then add your new worker with:
587
588 ```bash
589 heroku scale worker=1
590 ```
591
592 ## Changelog
593
594 See [CHANGELOG.md](https://github.com/rq/django-rq/blob/master/CHANGELOG.md).
595
596 ---
597
598 Django-RQ is maintained by [Stamps](https://stamps.id), an Indonesian based company that provides enterprise grade CRM and order management systems.