flask-log-request-id icon indicating copy to clipboard operation
flask-log-request-id copied to clipboard

Flask in Celery context

Open POD666 opened this issue 3 years ago • 0 comments
trafficstars

Hi, I have tried to use enable_request_id_propagation with celery but during debugging found this: image

I have a lot of things bound to my flask app (e.g. flask-sqlalchemy) so in celery, I just create an instance of my flask app to interact with DB and much more.

Since both flask and celery contexts are available, MultiContextRequestIdFetcher seems to handle it in the wrong way. I guess this code should be changed to iterate until a first non-empty value is returned instead of returning on a first non-exception result:

class MultiContextRequestIdFetcher(object):
    ...

    def __call__(self):
        for ctx_fetcher in self.ctx_fetchers:
            try:
                return ctx_fetcher()
            except ExecutedOutsideContext:
                continue
        return None

For now, I fixed it by reversing handlers in current_request_id during celery worker startup:

enable_request_id_propagation(celery)
current_request_id.ctx_fetchers = current_request_id.ctx_fetchers[::-1]

POD666 avatar May 07 '22 20:05 POD666