Name | django-rq JSON |
Version |
3.0.0
JSON |
| download |
home_page | https://github.com/rq/django-rq |
Summary | An app that provides django integration for RQ (Redis Queue) |
upload_time | 2024-10-28 15:40:27 |
maintainer | None |
docs_url | None |
author | Selwin Ong |
requires_python | None |
license | MIT |
keywords |
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
=========
Django-RQ
=========
|Build Status|
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.
=================
Support Django-RQ
=================
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>`_.
============
Requirements
============
* `Django <https://www.djangoproject.com/>`__ (3.2+)
* `RQ <https://github.com/nvie/rq>`__
============
Installation
============
* Install ``django-rq`` (or `download from PyPI <http://pypi.python.org/pypi/django-rq>`__):
.. code-block:: python
pip install django-rq
* Add ``django_rq`` to ``INSTALLED_APPS`` in ``settings.py``:
.. code-block:: python
INSTALLED_APPS = (
# other apps
"django_rq",
)
* Configure your queues in django's ``settings.py``:
.. code-block:: python
RQ_QUEUES = {
'default': {
'HOST': 'localhost',
'PORT': 6379,
'DB': 0,
'USERNAME': 'some-user',
'PASSWORD': 'some-password',
'DEFAULT_TIMEOUT': 360,
'REDIS_CLIENT_KWARGS': { # Eventual additional Redis connection arguments
'ssl_cert_reqs': None,
},
},
'with-sentinel': {
'SENTINELS': [('localhost', 26736), ('localhost', 26737)],
'MASTER_NAME': 'redismaster',
'DB': 0,
# Redis username/password
'USERNAME': 'redis-user',
'PASSWORD': 'secret',
'SOCKET_TIMEOUT': 0.3,
'CONNECTION_KWARGS': { # Eventual additional Redis connection arguments
'ssl': True
},
'SENTINEL_KWARGS': { # Eventual Sentinel connection arguments
# If Sentinel also has auth, username/password can be passed here
'username': 'sentinel-user',
'password': 'secret',
},
},
'high': {
'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku
'DEFAULT_TIMEOUT': 500,
},
'low': {
'HOST': 'localhost',
'PORT': 6379,
'DB': 0,
}
}
RQ_EXCEPTION_HANDLERS = ['path.to.my.handler'] # If you need custom exception handlers
* Include ``django_rq.urls`` in your ``urls.py``:
.. code-block:: python
urlpatterns += [
path('django-rq/', include('django_rq.urls'))
]
=====
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:
.. code-block:: python
import django_rq
django_rq.enqueue(func, foo, bar=baz)
* ``get_queue`` - returns an ``Queue`` instance.
.. code-block:: python
import django_rq
queue = django_rq.get_queue('high')
queue.enqueue(func, foo, bar=baz)
In addition to ``name`` argument, ``get_queue`` also accepts ``default_timeout``,
``is_async``, ``autocommit``, ``connection`` and ``queue_class`` arguments. For example:
.. code-block:: python
queue = django_rq.get_queue('default', autocommit=True, is_async=True, default_timeout=360)
queue.enqueue(func, foo, bar=baz)
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:
.. code-block:: python
import django_rq
import redis
redis_cursor = redis.StrictRedis(host='', port='', db='', password='')
high_queue = django_rq.get_queue('high', connection=redis_cursor)
low_queue = django_rq.get_queue('low', connection=redis_cursor)
* ``get_connection`` - accepts a single queue name argument (defaults to "default")
and returns a connection to the queue's Redis server:
.. code-block:: python
import django_rq
redis_conn = django_rq.get_connection('high')
* ``get_worker`` - accepts optional queue names and returns a new `RQ`
``Worker`` instance for specified queues (or ``default`` queue):
.. code-block:: python
import django_rq
worker = django_rq.get_worker() # Returns a worker for "default" queue
worker.work()
worker = django_rq.get_worker('low', 'high') # Returns a worker for "low" and "high"
@job decorator
--------------
To easily turn a callable into an RQ task, you can also use the ``@job``
decorator that comes with ``django_rq``:
.. code-block:: python
from django_rq import job
@job
def long_running_func():
pass
long_running_func.delay() # Enqueue function in "default" queue
@job('high')
def long_running_func():
pass
long_running_func.delay() # Enqueue function in "high" queue
You can pass in any arguments that RQ's job decorator accepts:
.. code-block:: python
@job('default', timeout=3600)
def long_running_func():
pass
long_running_func.delay() # Enqueue function with a timeout of 3600 seconds.
It's possible to specify default for ``result_ttl`` decorator keyword argument
via ``DEFAULT_RESULT_TTL`` setting:
.. code-block:: python
RQ = {
'DEFAULT_RESULT_TTL': 5000,
}
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.
Starting from version 2.10, running RQ's worker-pool is also supported::
python manage.py rqworker-pool default low medium --num-workers 4
Support for Scheduled Jobs
--------------------------
With RQ 1.2.0. you can use `built-in scheduler <https://python-rq.org/docs/scheduling/>`__
for your jobs. For example:
.. code-block:: python
from django_rq.queues import get_queue
queue = get_queue('default')
job = queue.enqueue_at(datetime(2020, 10, 10), func)
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 <https://github.com/ui/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:
.. code-block:: python
import django_rq
scheduler = django_rq.get_scheduler('default')
job = scheduler.enqueue_at(datetime(2020, 10, 10), func)
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 <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>`__.)
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`:
.. code-block:: python
CACHES = {
'redis-cache': {
'BACKEND': 'redis_cache.cache.RedisCache',
'LOCATION': 'localhost:6379:1',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
'MAX_ENTRIES': 5000,
},
},
}
RQ_QUEUES = {
'high': {
'USE_REDIS_CACHE': 'redis-cache',
},
'low': {
'USE_REDIS_CACHE': 'redis-cache',
},
}
Suspending and Resuming Workers
-------------------------------
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.
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.
.. code-block:: bash
# Suspend indefinitely
python manage.py rqsuspend
# Suspend for a specific duration (in seconds) then automatically
# resume work again.
python manage.py rqsuspend -d 600
# Resume work again.
python manage.py rqresume
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>``.
.. image:: demo-django-rq-json-dashboard.png
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>`__.
Additionally, these statistics are also accessible from the command line.
.. code-block:: bash
python manage.py rqstats
python manage.py rqstats --interval=1 # Refreshes every second
python manage.py rqstats --json # Output as JSON
python manage.py rqstats --yaml # Output as YAML
.. image:: demo-django-rq-cli-dashboard.gif
Configuring Sentry
-------------------
Sentry
should be configured within the Django ``settings.py`` as described in the `Sentry docs <https://docs.sentry.io/platforms/python/django/>`__.
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:
.. code-block:: python
{
'debug': options.get('sentry_debug'),
'ca_certs': options.get('sentry_ca_certs'),
'integrations': [RedisIntegration(), RqIntegration(), DjangoIntegration()]
}
Configuring Logging
-------------------
RQ uses Python's ``logging``, this means you can easily configure ``rqworker``'s logging mechanism in django's
``settings.py``. For example:
.. code-block:: python
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"rq_console": {
"format": "%(asctime)s %(message)s",
"datefmt": "%H:%M:%S",
},
},
"handlers": {
"rq_console": {
"level": "DEBUG",
"class": "rq.logutils.ColorizingStreamHandler",
"formatter": "rq_console",
"exclude": ["%(asctime)s"],
},
},
'loggers': {
"rq.worker": {
"handlers": ["rq_console", "sentry"],
"level": "DEBUG"
},
}
}
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``:
.. code-block:: python
RQ_QUEUES = {
'default': {
'HOST': 'localhost',
'PORT': 6379,
'DB': 0,
'QUEUE_CLASS': 'module.path.CustomClass',
}
}
or you can specify ``DjangoRQ`` to use a custom class for all your queues in ``RQ`` settings:
.. code-block:: python
RQ = {
'QUEUE_CLASS': 'module.path.CustomClass',
}
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:
.. code-block:: python
RQ = {
'JOB_CLASS': 'module.path.CustomJobClass',
'WORKER_CLASS': 'module.path.CustomWorkerClass',
}
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:
.. code-block:: python
from django.test import TestCase
from django_rq import get_worker
class MyTest(TestCase):
def test_something_that_creates_jobs(self):
... # Stuff that init jobs.
get_worker().work(burst=True) # Processes all jobs then stop.
... # Asserts that the job stuff is done.
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:
.. code-block:: python
# ... Logic to set DEBUG and TESTING settings to True or False ...
# ... Regular RQ_QUEUES setup code ...
if DEBUG or TESTING:
for queueConfig in RQ_QUEUES.values():
queueConfig['ASYNC'] = False
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` 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
.. code-block:: bash
[Unit]
Description=Django-RQ Worker
After=network.target
[Service]
WorkingDirectory=<<path_to_your_project_folder>>
ExecStart=/home/ubuntu/.virtualenv/<<your_virtualenv>>/bin/python \
<<path_to_your_project_folder>>/manage.py \
rqworker high default low
[Install]
WantedBy=multi-user.target
Enable and start the service
.. code-block:: bash
sudo systemctl enable rqworker
sudo systemctl start rqworker
===================
Deploying on Heroku
===================
Add `django-rq` to your `requirements.txt` file with:
.. code-block:: bash
pip freeze > requirements.txt
Update your `Procfile` to:
.. code-block:: bash
web: gunicorn --pythonpath="$PWD/your_app_name" config.wsgi:application
worker: python your_app_name/manage.py rqworker high default low
Commit and re-deploy. Then add your new worker with:
.. code-block:: bash
heroku scale worker=1
=========
Changelog
=========
See `CHANGELOG.md <https://github.com/rq/django-rq/blob/master/CHANGELOG.md>`__.
.. |Build Status| image:: https://github.com/rq/django-rq/actions/workflows/test.yml/badge.svg
:target: https://github.com/rq/django-rq/actions/workflows/test.yml
Raw data
{
"_id": null,
"home_page": "https://github.com/rq/django-rq",
"name": "django-rq",
"maintainer": null,
"docs_url": null,
"requires_python": null,
"maintainer_email": null,
"keywords": null,
"author": "Selwin Ong",
"author_email": "selwin.ong@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/e1/71/0412cc1bd0f4026e727ad9fa8f407a2225b6ce593e15ed6fcccebeef50ef/django-rq-3.0.0.tar.gz",
"platform": null,
"description": "=========\nDjango-RQ\n=========\n\n|Build Status|\n\nDjango integration with `RQ <https://github.com/nvie/rq>`__, a `Redis <http://redis.io/>`__\nbased Python queuing library. `Django-RQ <https://github.com/rq/django-rq>`__ is a\nsimple app that allows you to configure your queues in django's ``settings.py``\nand easily use them in your project.\n\n=================\nSupport Django-RQ\n=================\n\nIf 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>`_.\n\n============\nRequirements\n============\n\n* `Django <https://www.djangoproject.com/>`__ (3.2+)\n* `RQ <https://github.com/nvie/rq>`__\n\n============\nInstallation\n============\n\n* Install ``django-rq`` (or `download from PyPI <http://pypi.python.org/pypi/django-rq>`__):\n\n.. code-block:: python\n\n pip install django-rq\n\n* Add ``django_rq`` to ``INSTALLED_APPS`` in ``settings.py``:\n\n.. code-block:: python\n\n INSTALLED_APPS = (\n # other apps\n \"django_rq\",\n )\n\n* Configure your queues in django's ``settings.py``:\n\n.. code-block:: python\n\n RQ_QUEUES = {\n 'default': {\n 'HOST': 'localhost',\n 'PORT': 6379,\n 'DB': 0,\n 'USERNAME': 'some-user',\n 'PASSWORD': 'some-password',\n 'DEFAULT_TIMEOUT': 360,\n 'REDIS_CLIENT_KWARGS': { # Eventual additional Redis connection arguments\n 'ssl_cert_reqs': None,\n },\n },\n 'with-sentinel': {\n 'SENTINELS': [('localhost', 26736), ('localhost', 26737)],\n 'MASTER_NAME': 'redismaster',\n 'DB': 0,\n # Redis username/password\n 'USERNAME': 'redis-user',\n 'PASSWORD': 'secret',\n 'SOCKET_TIMEOUT': 0.3,\n 'CONNECTION_KWARGS': { # Eventual additional Redis connection arguments\n 'ssl': True\n },\n 'SENTINEL_KWARGS': { # Eventual Sentinel connection arguments\n # If Sentinel also has auth, username/password can be passed here\n 'username': 'sentinel-user',\n 'password': 'secret',\n },\n },\n 'high': {\n 'URL': os.getenv('REDISTOGO_URL', 'redis://localhost:6379/0'), # If you're on Heroku\n 'DEFAULT_TIMEOUT': 500,\n },\n 'low': {\n 'HOST': 'localhost',\n 'PORT': 6379,\n 'DB': 0,\n }\n }\n\n RQ_EXCEPTION_HANDLERS = ['path.to.my.handler'] # If you need custom exception handlers\n\n* Include ``django_rq.urls`` in your ``urls.py``:\n\n.. code-block:: python\n\n urlpatterns += [\n path('django-rq/', include('django_rq.urls'))\n ]\n\n=====\nUsage\n=====\n\nPutting jobs in the queue\n-------------------------\n\n`Django-RQ` allows you to easily put jobs into any of the queues defined in\n``settings.py``. It comes with a few utility functions:\n\n* ``enqueue`` - push a job to the ``default`` queue:\n\n.. code-block:: python\n\n import django_rq\n django_rq.enqueue(func, foo, bar=baz)\n\n* ``get_queue`` - returns an ``Queue`` instance.\n\n.. code-block:: python\n\n import django_rq\n queue = django_rq.get_queue('high')\n queue.enqueue(func, foo, bar=baz)\n\nIn addition to ``name`` argument, ``get_queue`` also accepts ``default_timeout``,\n``is_async``, ``autocommit``, ``connection`` and ``queue_class`` arguments. For example:\n\n.. code-block:: python\n\n queue = django_rq.get_queue('default', autocommit=True, is_async=True, default_timeout=360)\n queue.enqueue(func, foo, bar=baz)\n\nYou can provide your own singleton Redis connection object to this function so that it will not\ncreate a new connection object for each queue definition. This will help you limit\nnumber of connections to Redis server. For example:\n\n.. code-block:: python\n\n import django_rq\n import redis\n redis_cursor = redis.StrictRedis(host='', port='', db='', password='')\n high_queue = django_rq.get_queue('high', connection=redis_cursor)\n low_queue = django_rq.get_queue('low', connection=redis_cursor)\n\n\n* ``get_connection`` - accepts a single queue name argument (defaults to \"default\")\n and returns a connection to the queue's Redis server:\n\n.. code-block:: python\n\n import django_rq\n redis_conn = django_rq.get_connection('high')\n\n* ``get_worker`` - accepts optional queue names and returns a new `RQ`\n ``Worker`` instance for specified queues (or ``default`` queue):\n\n.. code-block:: python\n\n import django_rq\n worker = django_rq.get_worker() # Returns a worker for \"default\" queue\n worker.work()\n worker = django_rq.get_worker('low', 'high') # Returns a worker for \"low\" and \"high\"\n\n\n@job decorator\n--------------\n\nTo easily turn a callable into an RQ task, you can also use the ``@job``\ndecorator that comes with ``django_rq``:\n\n.. code-block:: python\n\n from django_rq import job\n\n @job\n def long_running_func():\n pass\n long_running_func.delay() # Enqueue function in \"default\" queue\n\n @job('high')\n def long_running_func():\n pass\n long_running_func.delay() # Enqueue function in \"high\" queue\n\nYou can pass in any arguments that RQ's job decorator accepts:\n\n.. code-block:: python\n\n @job('default', timeout=3600)\n def long_running_func():\n pass\n long_running_func.delay() # Enqueue function with a timeout of 3600 seconds.\n\nIt's possible to specify default for ``result_ttl`` decorator keyword argument\nvia ``DEFAULT_RESULT_TTL`` setting:\n\n.. code-block:: python\n\n RQ = {\n 'DEFAULT_RESULT_TTL': 5000,\n }\n\nWith this setting, job decorator will set ``result_ttl`` to 5000 unless it's\nspecified explicitly.\n\n\nRunning workers\n---------------\ndjango_rq provides a management command that starts a worker for every queue\nspecified as arguments::\n\n python manage.py rqworker high default low\n\nIf you want to run ``rqworker`` in burst mode, you can pass in the ``--burst`` flag::\n\n python manage.py rqworker high default low --burst\n\nIf you need to use custom worker, job or queue classes, it is best to use global settings\n(see `Custom queue classes`_ and `Custom job and worker classes`_). However, it is also possible\nto override such settings with command line options as follows.\n\nTo use a custom worker class, you can pass in the ``--worker-class`` flag\nwith the path to your worker::\n\n python manage.py rqworker high default low --worker-class 'path.to.GeventWorker'\n\nTo use a custom queue class, you can pass in the ``--queue-class`` flag\nwith the path to your queue class::\n\n python manage.py rqworker high default low --queue-class 'path.to.CustomQueue'\n\nTo use a custom job class, provide ``--job-class`` flag.\n\nStarting from version 2.10, running RQ's worker-pool is also supported::\n\n python manage.py rqworker-pool default low medium --num-workers 4\n\nSupport for Scheduled Jobs\n--------------------------\n\nWith RQ 1.2.0. you can use `built-in scheduler <https://python-rq.org/docs/scheduling/>`__\nfor your jobs. For example:\n\n.. code-block:: python\n\n from django_rq.queues import get_queue\n queue = get_queue('default')\n job = queue.enqueue_at(datetime(2020, 10, 10), func)\n\nIf you are using built-in scheduler you have to start workers with scheduler support::\n\n python manage.py rqworker --with-scheduler\n\n\nAlternatively you can use `RQ Scheduler <https://github.com/ui/rq-scheduler>`__.\nAfter install you can also use the ``get_scheduler`` function to return a\n``Scheduler`` instance for queues defined in settings.py's ``RQ_QUEUES``.\nFor example:\n\n.. code-block:: python\n\n import django_rq\n scheduler = django_rq.get_scheduler('default')\n job = scheduler.enqueue_at(datetime(2020, 10, 10), func)\n\nYou can also use the management command ``rqscheduler`` to start the scheduler::\n\n python manage.py rqscheduler\n\n\nSupport for django-redis and django-redis-cache\n-----------------------------------------------\n\nIf you have `django-redis <https://django-redis.readthedocs.org/>`__ or\n`django-redis-cache <https://github.com/sebleier/django-redis-cache/>`__\ninstalled, you can instruct django_rq to use the same connection information\nfrom your Redis cache. This has two advantages: it's DRY and it takes advantage\nof any optimization that may be going on in your cache setup (like using\nconnection pooling or `Hiredis <https://github.com/redis/hiredis>`__.)\n\nTo use configure it, use a dict with the key ``USE_REDIS_CACHE`` pointing to the\nname of the desired cache in your ``RQ_QUEUES`` dict. It goes without saying\nthat the chosen cache must exist and use the Redis backend. See your respective\nRedis cache package docs for configuration instructions. It's also important to\npoint out that since the django-redis-cache ``ShardedClient`` splits the cache\nover multiple Redis connections, it does not work.\n\nHere is an example settings fragment for `django-redis`:\n\n.. code-block:: python\n\n CACHES = {\n 'redis-cache': {\n 'BACKEND': 'redis_cache.cache.RedisCache',\n 'LOCATION': 'localhost:6379:1',\n 'OPTIONS': {\n 'CLIENT_CLASS': 'django_redis.client.DefaultClient',\n 'MAX_ENTRIES': 5000,\n },\n },\n }\n\n RQ_QUEUES = {\n 'high': {\n 'USE_REDIS_CACHE': 'redis-cache',\n },\n 'low': {\n 'USE_REDIS_CACHE': 'redis-cache',\n },\n }\n\n\nSuspending and Resuming Workers\n-------------------------------\n\nSometimes you may want to suspend RQ to prevent it from processing new jobs.\nA classic example is during the initial phase of a deployment script or in advance\nof putting your site into maintenance mode. This is particularly helpful when\nyou have jobs that are relatively long-running and might otherwise be forcibly\nkilled during the deploy.\n\nThe `suspend` command stops workers on _all_ queues (in a single Redis database)\nfrom picking up new jobs. However currently running jobs will continue until\ncompletion.\n\n.. code-block:: bash\n\n # Suspend indefinitely\n python manage.py rqsuspend\n\n # Suspend for a specific duration (in seconds) then automatically\n # resume work again.\n python manage.py rqsuspend -d 600\n\n # Resume work again.\n python manage.py rqresume\n\n\nQueue Statistics\n----------------\n\n``django_rq`` also provides a dashboard to monitor the status of your queues at\n``/django-rq/`` (or whatever URL you set in your ``urls.py`` during installation.\n\nYou can also add a link to this dashboard link in ``/admin`` by adding\n``RQ_SHOW_ADMIN_LINK = True`` in ``settings.py``. Be careful though, this will\noverride the default admin template so it may interfere with other apps that\nmodifies the default admin template.\n\nThese statistics are also available in JSON format via\n``/django-rq/stats.json``, which is accessible to staff members.\nIf you need to access this view via other\nHTTP clients (for monitoring purposes), you can define ``RQ_API_TOKEN`` and access it via\n``/django-rq/stats.json/<API_TOKEN>``.\n\n.. image:: demo-django-rq-json-dashboard.png\n\nNote: Statistics of scheduled jobs display jobs from `RQ built-in scheduler <https://python-rq.org/docs/scheduling/>`__,\nnot optional `RQ scheduler <https://github.com/rq/rq-scheduler>`__.\n\nAdditionally, these statistics are also accessible from the command line.\n\n.. code-block:: bash\n\n python manage.py rqstats\n python manage.py rqstats --interval=1 # Refreshes every second\n python manage.py rqstats --json # Output as JSON\n python manage.py rqstats --yaml # Output as YAML\n\n.. image:: demo-django-rq-cli-dashboard.gif\n\nConfiguring Sentry\n-------------------\nSentry\nshould be configured within the Django ``settings.py`` as described in the `Sentry docs <https://docs.sentry.io/platforms/python/django/>`__.\n\nYou can override the default Django Sentry configuration when running the ``rqworker`` command\nby passing the ``sentry-dsn`` option:\n\n``./manage.py rqworker --sentry-dsn=https://*****@sentry.io/222222``\n\nThis will override any existing Django configuration and reinitialise Sentry,\nsetting the following Sentry options:\n\n.. code-block:: python\n\n {\n 'debug': options.get('sentry_debug'),\n 'ca_certs': options.get('sentry_ca_certs'),\n 'integrations': [RedisIntegration(), RqIntegration(), DjangoIntegration()]\n }\n\n\nConfiguring Logging\n-------------------\n\nRQ uses Python's ``logging``, this means you can easily configure ``rqworker``'s logging mechanism in django's\n``settings.py``. For example:\n\n.. code-block:: python\n\n LOGGING = {\n \"version\": 1,\n \"disable_existing_loggers\": False,\n \"formatters\": {\n \"rq_console\": {\n \"format\": \"%(asctime)s %(message)s\",\n \"datefmt\": \"%H:%M:%S\",\n },\n },\n \"handlers\": {\n \"rq_console\": {\n \"level\": \"DEBUG\",\n \"class\": \"rq.logutils.ColorizingStreamHandler\",\n \"formatter\": \"rq_console\",\n \"exclude\": [\"%(asctime)s\"],\n },\n },\n 'loggers': {\n \"rq.worker\": {\n \"handlers\": [\"rq_console\", \"sentry\"],\n \"level\": \"DEBUG\"\n },\n }\n }\n\n\nCustom Queue Classes\n--------------------\n\nBy default, every queue will use ``DjangoRQ`` class. If you want to use a custom queue class, you can do so\nby adding a ``QUEUE_CLASS`` option on a per queue basis in ``RQ_QUEUES``:\n\n.. code-block:: python\n\n RQ_QUEUES = {\n 'default': {\n 'HOST': 'localhost',\n 'PORT': 6379,\n 'DB': 0,\n 'QUEUE_CLASS': 'module.path.CustomClass',\n }\n }\n\nor you can specify ``DjangoRQ`` to use a custom class for all your queues in ``RQ`` settings:\n\n.. code-block:: python\n\n RQ = {\n 'QUEUE_CLASS': 'module.path.CustomClass',\n }\n\nCustom queue classes should inherit from ``django_rq.queues.DjangoRQ``.\n\nIf you are using more than one queue class (not recommended), be sure to only run workers\non queues with same queue class. For example if you have two queues defined in ``RQ_QUEUES`` and\none has custom class specified, you would have to run at least two separate workers for each\nqueue.\n\nCustom Job and Worker Classes\n-----------------------------\n\nSimilarly to custom queue classes, global custom job and worker classes can be configured using\n``JOB_CLASS`` and ``WORKER_CLASS`` settings:\n\n.. code-block:: python\n\n RQ = {\n 'JOB_CLASS': 'module.path.CustomJobClass',\n 'WORKER_CLASS': 'module.path.CustomWorkerClass',\n }\n\nCustom job class should inherit from ``rq.job.Job``. It will be used for all jobs\nif configured.\n\nCustom worker class should inherit from ``rq.worker.Worker``. It will be used for running\nall workers unless overridden by ``rqworker`` management command ``worker-class`` option.\n\nTesting Tip\n-----------\n\nFor an easier testing process, you can run a worker synchronously this way:\n\n.. code-block:: python\n\n from django.test import TestCase\n from django_rq import get_worker\n\n class MyTest(TestCase):\n def test_something_that_creates_jobs(self):\n ... # Stuff that init jobs.\n get_worker().work(burst=True) # Processes all jobs then stop.\n ... # Asserts that the job stuff is done.\n\nSynchronous Mode\n----------------\n\nYou can set the option ``ASYNC`` to ``False`` to make synchronous operation the\ndefault for a given queue. This will cause jobs to execute immediately and on\nthe same thread as they are dispatched, which is useful for testing and\ndebugging. For example, you might add the following after you queue\nconfiguration in your settings file:\n\n.. code-block:: python\n\n # ... Logic to set DEBUG and TESTING settings to True or False ...\n\n # ... Regular RQ_QUEUES setup code ...\n\n if DEBUG or TESTING:\n for queueConfig in RQ_QUEUES.values():\n queueConfig['ASYNC'] = False\n\nNote that setting the ``is_async`` parameter explicitly when calling ``get_queue``\nwill override this setting.\n\n=============\nRunning Tests\n=============\n\nTo run ``django_rq``'s test suite::\n\n `which django-admin` test django_rq --settings=django_rq.tests.settings --pythonpath=.\n\n===================\nDeploying on Ubuntu\n===================\n\nCreate an rqworker service that runs the high, default, and low queues.\n\nsudo vi /etc/systemd/system/rqworker.service\n\n.. code-block:: bash\n\n [Unit]\n Description=Django-RQ Worker\n After=network.target\n\n [Service]\n WorkingDirectory=<<path_to_your_project_folder>>\n ExecStart=/home/ubuntu/.virtualenv/<<your_virtualenv>>/bin/python \\\n <<path_to_your_project_folder>>/manage.py \\\n rqworker high default low\n\n [Install]\n WantedBy=multi-user.target\n\nEnable and start the service\n\n.. code-block:: bash\n\n sudo systemctl enable rqworker\n sudo systemctl start rqworker\n\n===================\nDeploying on Heroku\n===================\n\nAdd `django-rq` to your `requirements.txt` file with:\n\n.. code-block:: bash\n\n pip freeze > requirements.txt\n\nUpdate your `Procfile` to:\n\n.. code-block:: bash\n\n web: gunicorn --pythonpath=\"$PWD/your_app_name\" config.wsgi:application\n\n worker: python your_app_name/manage.py rqworker high default low\n\nCommit and re-deploy. Then add your new worker with:\n\n.. code-block:: bash\n\n heroku scale worker=1\n\n=========\nChangelog\n=========\n\nSee `CHANGELOG.md <https://github.com/rq/django-rq/blob/master/CHANGELOG.md>`__.\n\n\n.. |Build Status| image:: https://github.com/rq/django-rq/actions/workflows/test.yml/badge.svg\n :target: https://github.com/rq/django-rq/actions/workflows/test.yml\n\n\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "An app that provides django integration for RQ (Redis Queue)",
"version": "3.0.0",
"project_urls": {
"Homepage": "https://github.com/rq/django-rq"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "fe9a6a9cdc19805c31019021f582728de5493ef4381c391434f64af6e4b5121c",
"md5": "104ce37b98b5c5e574f7b1e81c6a632c",
"sha256": "bd2ef287a28301f64c4282293648e4f8c6076dd895a545c9c6b98bde4a82a4ce"
},
"downloads": -1,
"filename": "django_rq-3.0.0-py2.py3-none-any.whl",
"has_sig": false,
"md5_digest": "104ce37b98b5c5e574f7b1e81c6a632c",
"packagetype": "bdist_wheel",
"python_version": "py2.py3",
"requires_python": null,
"size": 64432,
"upload_time": "2024-10-28T15:40:25",
"upload_time_iso_8601": "2024-10-28T15:40:25.686825Z",
"url": "https://files.pythonhosted.org/packages/fe/9a/6a9cdc19805c31019021f582728de5493ef4381c391434f64af6e4b5121c/django_rq-3.0.0-py2.py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "e1710412cc1bd0f4026e727ad9fa8f407a2225b6ce593e15ed6fcccebeef50ef",
"md5": "c40dfbc94bf0d8f09abfa0b4cee2d3e3",
"sha256": "7bdadb85d9909c118cf1ee1b9bdd1a74ebf141bf8f3c2de2409fcac6080f67ac"
},
"downloads": -1,
"filename": "django-rq-3.0.0.tar.gz",
"has_sig": false,
"md5_digest": "c40dfbc94bf0d8f09abfa0b4cee2d3e3",
"packagetype": "sdist",
"python_version": "source",
"requires_python": null,
"size": 53356,
"upload_time": "2024-10-28T15:40:27",
"upload_time_iso_8601": "2024-10-28T15:40:27.633552Z",
"url": "https://files.pythonhosted.org/packages/e1/71/0412cc1bd0f4026e727ad9fa8f407a2225b6ce593e15ed6fcccebeef50ef/django-rq-3.0.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-10-28 15:40:27",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "rq",
"github_project": "django-rq",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "django-rq"
}