Skip to content

Instantly share code, notes, and snippets.

@EJH2
Last active October 31, 2019 02:16
Show Gist options
  • Save EJH2/fe94d5013a58c9f668fcb9d8455d5622 to your computer and use it in GitHub Desktop.
Save EJH2/fe94d5013a58c9f668fcb9d8455d5622 to your computer and use it in GitHub Desktop.
<!--
display_progress.html
The channels library doesn't provide an easy way to reference URLs in templates, so hardcoding the URL is necessary
!-->
<script src="{% static 'celery_progress/celery_progress.js' %}"></script>
<script src="{% static 'celery_progress/celery_progress_websockets.js' %}"></script>
...
<script>
document.addEventListener("DOMContentLoaded", function () {
var progressUrl = "/ws/progress/{{ task_id }}/";
CeleryWebSocketProgressBar.initProgressBar(progressUrl);
});
</script>
# myproject/settings.py
INSTALLED_APPS = [
...
'channels',
]
ASGI_APPLICATION = 'myproject.routing.application'
CHANNEL_LAYERS = {
'default': {
# This example is assuming you use redis, in which case `channels_redis` is another dependency.
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
"hosts": [
{
'address': (127.0.0.1, 6379), # These values should match your celery backend
'db': 0
}
],
},
},
}
# myproject/routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import celery_progress.routing
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter(
celery_progress.routing.websocket_urlpatterns
)
),
})
# myproject/celery.py
## `app` represents the name of your Celery instance, so add this line after you define it
app.autodiscover_tasks(packages=['celery_progress'])
# myapp/tasks.py
from celery import shared_task
from celery_progress.backend import WebSocketProgressRecorder
import time
@shared_task(bind=True)
def my_task(self, seconds):
progress_recorder = WebSocketProgressRecorder(self)
result = 0
for i in range(seconds):
time.sleep(1)
result += i
progress_recorder.set_progress(i + 1, seconds)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment