Scott Vitale, Founder @
Relying on an external API means suffering when that API experiences...
pip install celery
app / settings.py
CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672'
CELERY_RESULT_BACKEND = CELERY_BROKER_URL
app / celery.py
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'server.settings')
from django.conf import settings
celery_app = Celery('kickasspets')
# Using a string here means the worker don't have to serialize the
# configuration object to child processes.
celery_app.config_from_object('django.conf:settings')
# Load task modules from all registered Django app configs.
celery_app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
app / __init__.py
from __future__ import absolute_import, unicode_literals
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import celery_app
__all__ = ['celery_app']
app / views.py
import requests
def get_turtle_descriptions():
# Get turtle descriptions from the API, deserialize, and return as
# python list
api_response = requests.get(
'http://localhost:8001/turtle-api/descriptions')
return api_response.json()['turtles']
class TurtleView(View):
def get(self, request):
descriptions = get_turtle_descriptions()
return render(request, 'turtles.html', {
'page': 'turtles',
'descriptions': descriptions
})
app / tasks.py
from __future__ import absolute_import
from celery import shared_task
import requests
@shared_task
def get_turtle_descriptions():
# Get turtle descriptions from the API, deserialize, and return as
# python list
api_response = requests.get(
'http://localhost:8001/turtle-api/descriptions')
return api_response.json()['turtles']
app / views.py
from __future__ import absolute_import
from . import tasks
class TurtleView(View):
def get(self, request):
task = tasks.get_turtle_descriptions.delay()
return render(request, 'turtles.html', {
'page': 'turtles',
'task_id': task.id
})
app / urls.py
url(r'^status/(?P<task_id>>[a-f\d\-]+)', StatusView.as_view())
app / views.py
from __future__ import absolute_import
from celery.result import AsyncResult
class StatusView(View):
def get(self, request, task_id):
# Get task by ID and its status
task_result = AsyncResult(task_id)
task_is_complete = task_result.ready()
if task_is_complete:
# Retrieve response data
data = task_result.get()
else:
data = None
return JsonResponse({
'complete': task_is_complete,
'data': data
})
celery -A app worker -l info