├── .gitignore ├── LICENSE ├── README.md ├── docker-compose.yml ├── project ├── Dockerfile ├── app │ ├── __init__.py │ └── tasks.py ├── logs │ └── celery.log ├── requirements.txt └── test.py └── test.sh /.gitignore: -------------------------------------------------------------------------------- 1 | env 2 | __pycache__ 3 | .DS_Store 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | Copyright (c) 2022 TestDriven.io 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 5 | 6 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 7 | 8 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Falcon + Celery 2 | 3 | Example of how to handle background processes with Falcon, Celery, and Docker 4 | 5 | ### Quick Start 6 | 7 | Spin up the containers: 8 | 9 | ```sh 10 | $ docker-compose up -d 11 | ``` 12 | 13 | Open your browser to http://localhost:8000/ping to view the app or to http://localhost:5555 to view the Flower dashboard. 14 | 15 | Trigger a new task: 16 | 17 | ```sh 18 | $ curl -X POST http://localhost:8000/create \ 19 | -d '{"number":"3"}' \ 20 | -H "Content-Type: application/json" 21 | ``` 22 | 23 | Check the status: 24 | 25 | ```sh 26 | $ curl http://localhost:8000/status/ 27 | ``` 28 | 29 | ### Want to learn how to build this? 30 | 31 | Check out the [post](https://testdriven.io/asynchronous-tasks-with-falcon-and-celery). 32 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | 3 | services: 4 | 5 | web: 6 | build: ./project 7 | image: web 8 | container_name: web 9 | ports: 10 | - 8000:8000 11 | volumes: 12 | - ./project:/usr/src/app 13 | command: gunicorn -b 0.0.0.0:8000 app:app 14 | environment: 15 | - CELERY_BROKER=redis://redis:6379/0 16 | - CELERY_BACKEND=redis://redis:6379/0 17 | depends_on: 18 | - redis 19 | 20 | celery: 21 | image: web 22 | volumes: 23 | - ./project:/usr/src/app 24 | - ./project/logs:/usr/src/app/logs 25 | command: celery -A app.tasks worker --loglevel=info --logfile=logs/celery.log 26 | environment: 27 | - CELERY_BROKER=redis://redis:6379/0 28 | - CELERY_BACKEND=redis://redis:6379/0 29 | depends_on: 30 | - web 31 | - redis 32 | 33 | redis: 34 | image: redis:7-alpine 35 | 36 | monitor: 37 | build: ./project 38 | image: web 39 | ports: 40 | - 5555:5555 41 | command: celery flower -A app.tasks --port=5555 --broker=redis://redis:6379/0 42 | environment: 43 | - CELERY_BROKER=redis://redis:6379/0 44 | - CELERY_BACKEND=redis://redis:6379/0 45 | depends_on: 46 | - web 47 | - redis -------------------------------------------------------------------------------- /project/Dockerfile: -------------------------------------------------------------------------------- 1 | # base image 2 | FROM python:3.11-alpine 3 | 4 | # set working directory 5 | WORKDIR /usr/src/app 6 | 7 | # add requirements 8 | COPY ./requirements.txt /usr/src/app/requirements.txt 9 | 10 | # install requirements 11 | RUN pip install -r requirements.txt 12 | 13 | # add app 14 | COPY . /usr/src/app 15 | -------------------------------------------------------------------------------- /project/app/__init__.py: -------------------------------------------------------------------------------- 1 | # project/app/__init__.py 2 | 3 | 4 | import json 5 | 6 | import falcon 7 | from celery.result import AsyncResult 8 | 9 | from app.tasks import fib 10 | 11 | 12 | class Ping(object): 13 | def on_get(self, req, resp): 14 | resp.status = falcon.HTTP_200 15 | resp.text = json.dumps('pong!') 16 | 17 | 18 | class CreateTask(object): 19 | 20 | def on_post(self, req, resp): 21 | raw_json = req.stream.read() 22 | result = json.loads(raw_json) 23 | task = fib.delay(int(result['number'])) 24 | resp.status = falcon.HTTP_200 25 | result = { 26 | 'status': 'success', 27 | 'data': { 28 | 'task_id': task.id 29 | } 30 | } 31 | resp.text = json.dumps(result) 32 | 33 | 34 | class CheckStatus(object): 35 | 36 | def on_get(self, req, resp, task_id): 37 | task_result = AsyncResult(task_id) 38 | result = {'status': task_result.status, 'result': task_result.result} 39 | resp.status = falcon.HTTP_200 40 | resp.text = json.dumps(result) 41 | 42 | 43 | app = falcon.App() 44 | 45 | app.add_route('/ping', Ping()) 46 | app.add_route('/create', CreateTask()) 47 | app.add_route('/status/{task_id}', CheckStatus()) 48 | -------------------------------------------------------------------------------- /project/app/tasks.py: -------------------------------------------------------------------------------- 1 | # project/app/tasks.py 2 | 3 | 4 | import os 5 | from time import sleep 6 | 7 | import celery 8 | 9 | 10 | CELERY_BROKER = os.environ.get('CELERY_BROKER') 11 | CELERY_BACKEND = os.environ.get('CELERY_BACKEND') 12 | 13 | app = celery.Celery('tasks', broker=CELERY_BROKER, backend=CELERY_BACKEND) 14 | 15 | 16 | @app.task 17 | def fib(n): 18 | sleep(2) # simulate slow computation 19 | if n < 0: 20 | return [] 21 | elif n == 0: 22 | return [0] 23 | elif n == 1: 24 | return [0, 1] 25 | else: 26 | results = fib(n - 1) 27 | results.append(results[-1] + results[-2]) 28 | return results 29 | -------------------------------------------------------------------------------- /project/logs/celery.log: -------------------------------------------------------------------------------- 1 | [2022-11-15 17:36:34,506: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error -2 connecting to redis:6379. Name does not resolve.. 2 | Trying again in 2.00 seconds... (1/100) 3 | 4 | [2022-11-15 17:36:36,521: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error -2 connecting to redis:6379. Name does not resolve.. 5 | Trying again in 4.00 seconds... (2/100) 6 | 7 | [2022-11-15 17:36:40,541: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error -2 connecting to redis:6379. Name does not resolve.. 8 | Trying again in 6.00 seconds... (3/100) 9 | 10 | [2022-11-15 17:36:46,573: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error -2 connecting to redis:6379. Name does not resolve.. 11 | Trying again in 8.00 seconds... (4/100) 12 | 13 | [2022-11-15 17:36:54,615: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error -2 connecting to redis:6379. Name does not resolve.. 14 | Trying again in 10.00 seconds... (5/100) 15 | 16 | [2022-11-15 17:37:04,639: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error -2 connecting to redis:6379. Name does not resolve.. 17 | Trying again in 12.00 seconds... (6/100) 18 | 19 | [2022-11-15 17:37:16,676: ERROR/MainProcess] consumer: Cannot connect to redis://redis:6379/0: Error -2 connecting to redis:6379. Name does not resolve.. 20 | Trying again in 14.00 seconds... (7/100) 21 | 22 | [2022-11-15 23:47:37,711: INFO/MainProcess] Connected to redis://redis:6379/0 23 | [2022-11-15 23:47:37,715: INFO/MainProcess] mingle: searching for neighbors 24 | [2022-11-15 23:47:38,725: INFO/MainProcess] mingle: all alone 25 | [2022-11-15 23:47:38,742: INFO/MainProcess] celery@7fdd7f545554 ready. 26 | [2022-11-15 23:47:42,568: INFO/MainProcess] Events of group {task} enabled by remote. 27 | -------------------------------------------------------------------------------- /project/requirements.txt: -------------------------------------------------------------------------------- 1 | celery==5.2.7 2 | falcon==3.1.0 3 | flower==1.2.0 4 | gunicorn==20.1.0 5 | redis==4.3.4 -------------------------------------------------------------------------------- /project/test.py: -------------------------------------------------------------------------------- 1 | # project/test.py 2 | 3 | 4 | import unittest 5 | from unittest.mock import patch 6 | 7 | from falcon import testing 8 | 9 | from app import app, tasks 10 | 11 | 12 | class TestAppRoutes(testing.TestCase): 13 | def setUp(self): 14 | super(TestAppRoutes, self).setUp() 15 | self.app = app 16 | 17 | def test_get_message(self): 18 | result = self.simulate_get('/ping') 19 | self.assertEqual(result.json, 'pong!') 20 | 21 | 22 | class TestCeleryTasks(unittest.TestCase): 23 | 24 | # def test_fib_task(self): 25 | # self.assertEqual(tasks.fib.run(-1), []) 26 | # self.assertEqual(tasks.fib.run(1), [0, 1]) 27 | # self.assertEqual(tasks.fib.run(3), [0, 1, 1, 2]) 28 | # self.assertEqual(tasks.fib.run(5), [0, 1, 1, 2, 3, 5]) 29 | 30 | @patch('app.tasks.fib') 31 | def test_mock_fib_task(self, mock_fib): 32 | mock_fib.run.return_value = [] 33 | self.assertEqual(tasks.fib.run(-1), []) 34 | mock_fib.run.return_value = [0, 1] 35 | self.assertEqual(tasks.fib.run(1), [0, 1]) 36 | mock_fib.run.return_value = [0, 1, 1, 2] 37 | self.assertEqual(tasks.fib.run(3), [0, 1, 1, 2]) 38 | mock_fib.run.return_value = [0, 1, 1, 2, 3, 5] 39 | self.assertEqual(tasks.fib.run(5), [0, 1, 1, 2, 3, 5]) 40 | 41 | 42 | if __name__ == '__main__': 43 | unittest.main() 44 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # trigger jobs 4 | test=`curl -X POST http://localhost:8000/create \ 5 | -d '{"number":"2"}' \ 6 | -H "Content-Type: application/json" \ 7 | -s \ 8 | | jq -r '.data.task_id'` 9 | 10 | # get status 11 | check=`curl http://localhost:8000/status/${test} -s | jq -r '.status'` 12 | 13 | while [ "$check" != "SUCCESS" ] 14 | do 15 | check=`curl http://localhost:8000/status/${test} -s | jq -r '.status'` 16 | echo $(curl http://localhost:8000/status/${test} -s) 17 | done 18 | --------------------------------------------------------------------------------