Skip to content

Commit b9cde7a

Browse files
committed
Add function to be used as a celery before_task_publish handler
1 parent a69c93e commit b9cde7a

2 files changed

Lines changed: 20 additions & 5 deletions

File tree

flask_log_request_id/extras/celery.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ def apply_async(self, *args, **kwargs):
2424

2525
return super(RequestIDAwareTask, self).apply_async(*args, **kwargs)
2626

27+
def add_request_id_header(headers=None, **kwargs):
28+
if _CELERY_X_HEADER not in headers:
29+
headers[_CELERY_X_HEADER] = current_request_id()
2730

2831
def ctx_celery_task_get_request_id():
2932
"""

tests/extras/celery_tests.py

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
1-
from celery import Celery
2-
import unittest
31
import mock
2+
import unittest
43

5-
6-
from flask_log_request_id.extras.celery import (
7-
RequestIDAwareTask, ctx_celery_task_get_request_id, ExecutedOutsideContext)
4+
from celery import Celery
5+
from flask_log_request_id.extras.celery import (ExecutedOutsideContext,
6+
RequestIDAwareTask,
7+
add_request_id_header,
8+
ctx_celery_task_get_request_id)
89

910

1011
class MockedTask(object):
@@ -63,6 +64,17 @@ def test_issue21_called_with_headers_None(self, mocked_current_request_id):
6364
'foo': 'bar'
6465
})
6566

67+
@mock.patch('flask_log_request_id.extras.celery.current_request_id')
68+
def test_before_task_publish_hooks_adds_header(self, mocked_current_request_id):
69+
mocked_current_request_id.return_value = 15
70+
71+
headers = {}
72+
add_request_id_header(headers={})
73+
print(headers)
74+
self.assertDictEqual(headers, {
75+
'x_request_id': 15
76+
})
77+
6678
@mock.patch('flask_log_request_id.extras.celery.current_task')
6779
def test_ctx_fetcher_outside_context(self, mocked_current_task):
6880

0 commit comments

Comments
 (0)