You can download this code by clicking the button below.
This code is now available for download.
This code defines a Celery task that fetches a random fact from an external API. The task makes an HTTP request to retrieve data and returns the result.
Technology Stack : Celery, requests
Code Type : Celery task
Code Difficulty : Intermediate
from celery import Celery
import random
import requests
def fetch_random_fact():
celery_app = Celery('tasks', broker='pyamqp://guest@localhost//')
@celery_app.task
def fetch_fact():
url = 'https://uselessfacts.jsph.pl/random.json'
response = requests.get(url)
if response.status_code == 200:
return response.json()['text']
else:
return 'Failed to fetch fact'
return fetch_fact.delay()