We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Django fixup appends to PYTHONPATH instead of prepending
Hi,

## Environment & Settings
**Celery version**: 4.2.1  (windowlicker)

# Steps to Reproduce

We are using Celery + Django in [dissemin](https://github.com/dissemin/dissemin/). We have a Django app named "statistics" which is actually a name conflicting with a Python 3 package from standard library. This should be fine in principle as long as the `PYTHONPATH` is set so that the local modules have precedence over the system ones.

When running Celery CLI, the system wide module has precedence over the local ones apparently.

I traced this issue back to [this `sys.path` tweak](https://github.com/celery/celery/blob/072dab85261599234341cc714b0d6f0caca20f00/celery/fixups/django.py#L60-L61), which is actually **appending** local path instead of prepending it.

I may have missed something, but is it important for some reason to append it and not prepend it in this context?

# Expected Behavior

Celery should load the local module as expected.

# Actual Behavior

```
# When going through celery CLI
sys.path == ['/Users/lverney/.local/share/virtualenvs/dissemin3/bin', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python36.zip', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6/site-packages', '/Users/lverney/.local/share/virtualenvs/dissemin3/src/django-allauth', '/Users/lverney/tmp/dissemin']

# Without celery
sys.path == ['', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python36.zip', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6/site-packages', '/Users/lverney/.local/share/virtualenvs/dissemin3/src/django-allauth']
```

We can see that current path is actually appended, not prepended. Therefore, "system" modules have precedence on the ones from the local project.


# Workaround

For people experiencing this issue, `PYTHONPATH=$(pwd) celery …` is a workaround.


Best,

/cc @wetneb who first noticed this issue.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `celery/fixups/django.py`
Content:
```
1 """Django-specific customization."""
2 from __future__ import absolute_import, unicode_literals
3 
4 import os
5 import sys
6 import warnings
7 from datetime import datetime
8 from importlib import import_module
9 
10 from kombu.utils.imports import symbol_by_name
11 from kombu.utils.objects import cached_property
12 
13 from celery import _state, signals
14 from celery.exceptions import FixupWarning, ImproperlyConfigured
15 
16 __all__ = ('DjangoFixup', 'fixup')
17 
18 ERR_NOT_INSTALLED = """\
19 Environment variable DJANGO_SETTINGS_MODULE is defined
20 but Django isn't installed.  Won't apply Django fix-ups!
21 """
22 
23 
24 def _maybe_close_fd(fh):
25     try:
26         os.close(fh.fileno())
27     except (AttributeError, OSError, TypeError):
28         # TypeError added for celery#962
29         pass
30 
31 
32 def _verify_django_version(django):
33     if django.VERSION < (1, 11):
34         raise ImproperlyConfigured('Celery 4.x requires Django 1.11 or later.')
35 
36 
37 def fixup(app, env='DJANGO_SETTINGS_MODULE'):
38     """Install Django fixup if settings module environment is set."""
39     SETTINGS_MODULE = os.environ.get(env)
40     if SETTINGS_MODULE and 'django' not in app.loader_cls.lower():
41         try:
42             import django  # noqa
43         except ImportError:
44             warnings.warn(FixupWarning(ERR_NOT_INSTALLED))
45         else:
46             _verify_django_version(django)
47             return DjangoFixup(app).install()
48 
49 
50 class DjangoFixup(object):
51     """Fixup installed when using Django."""
52 
53     def __init__(self, app):
54         self.app = app
55         if _state.default_app is None:
56             self.app.set_default()
57         self._worker_fixup = None
58 
59     def install(self):
60         # Need to add project directory to path
61         sys.path.append(os.getcwd())
62 
63         self._settings = symbol_by_name('django.conf:settings')
64         self.app.loader.now = self.now
65 
66         signals.import_modules.connect(self.on_import_modules)
67         signals.worker_init.connect(self.on_worker_init)
68         return self
69 
70     @property
71     def worker_fixup(self):
72         if self._worker_fixup is None:
73             self._worker_fixup = DjangoWorkerFixup(self.app)
74         return self._worker_fixup
75 
76     @worker_fixup.setter
77     def worker_fixup(self, value):
78         self._worker_fixup = value
79 
80     def on_import_modules(self, **kwargs):
81         # call django.setup() before task modules are imported
82         self.worker_fixup.validate_models()
83 
84     def on_worker_init(self, **kwargs):
85         self.worker_fixup.install()
86 
87     def now(self, utc=False):
88         return datetime.utcnow() if utc else self._now()
89 
90     def autodiscover_tasks(self):
91         from django.apps import apps
92         return [config.name for config in apps.get_app_configs()]
93 
94     @cached_property
95     def _now(self):
96         return symbol_by_name('django.utils.timezone:now')
97 
98 
99 class DjangoWorkerFixup(object):
100     _db_recycles = 0
101 
102     def __init__(self, app):
103         self.app = app
104         self.db_reuse_max = self.app.conf.get('CELERY_DB_REUSE_MAX', None)
105         self._db = import_module('django.db')
106         self._cache = import_module('django.core.cache')
107         self._settings = symbol_by_name('django.conf:settings')
108 
109         self.interface_errors = (
110             symbol_by_name('django.db.utils.InterfaceError'),
111         )
112         self.DatabaseError = symbol_by_name('django.db:DatabaseError')
113 
114     def django_setup(self):
115         import django
116         django.setup()
117 
118     def validate_models(self):
119         from django.core.checks import run_checks
120         self.django_setup()
121         run_checks()
122 
123     def install(self):
124         signals.beat_embedded_init.connect(self.close_database)
125         signals.worker_ready.connect(self.on_worker_ready)
126         signals.task_prerun.connect(self.on_task_prerun)
127         signals.task_postrun.connect(self.on_task_postrun)
128         signals.worker_process_init.connect(self.on_worker_process_init)
129         self.close_database()
130         self.close_cache()
131         return self
132 
133     def on_worker_process_init(self, **kwargs):
134         # Child process must validate models again if on Windows,
135         # or if they were started using execv.
136         if os.environ.get('FORKED_BY_MULTIPROCESSING'):
137             self.validate_models()
138 
139         # close connections:
140         # the parent process may have established these,
141         # so need to close them.
142 
143         # calling db.close() on some DB connections will cause
144         # the inherited DB conn to also get broken in the parent
145         # process so we need to remove it without triggering any
146         # network IO that close() might cause.
147         for c in self._db.connections.all():
148             if c and c.connection:
149                 self._maybe_close_db_fd(c.connection)
150 
151         # use the _ version to avoid DB_REUSE preventing the conn.close() call
152         self._close_database()
153         self.close_cache()
154 
155     def _maybe_close_db_fd(self, fd):
156         try:
157             _maybe_close_fd(fd)
158         except self.interface_errors:
159             pass
160 
161     def on_task_prerun(self, sender, **kwargs):
162         """Called before every task."""
163         if not getattr(sender.request, 'is_eager', False):
164             self.close_database()
165 
166     def on_task_postrun(self, sender, **kwargs):
167         # See https://groups.google.com/group/django-users/
168         #            browse_thread/thread/78200863d0c07c6d/
169         if not getattr(sender.request, 'is_eager', False):
170             self.close_database()
171             self.close_cache()
172 
173     def close_database(self, **kwargs):
174         if not self.db_reuse_max:
175             return self._close_database()
176         if self._db_recycles >= self.db_reuse_max * 2:
177             self._db_recycles = 0
178             self._close_database()
179         self._db_recycles += 1
180 
181     def _close_database(self):
182         for conn in self._db.connections.all():
183             try:
184                 conn.close_if_unusable_or_obsolete()
185             except self.interface_errors:
186                 pass
187             except self.DatabaseError as exc:
188                 str_exc = str(exc)
189                 if 'closed' not in str_exc and 'not connected' not in str_exc:
190                     raise
191 
192     def close_cache(self):
193         try:
194             self._cache.close_caches()
195         except (TypeError, AttributeError):
196             pass
197 
198     def on_worker_ready(self, **kwargs):
199         if self._settings.DEBUG:
200             warnings.warn('Using settings.DEBUG leads to a memory leak, never '
201                           'use this setting in production environments!')
202
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/celery/fixups/django.py b/celery/fixups/django.py
--- a/celery/fixups/django.py
+++ b/celery/fixups/django.py
@@ -57,8 +57,10 @@
         self._worker_fixup = None
 
     def install(self):
-        # Need to add project directory to path
-        sys.path.append(os.getcwd())
+        # Need to add project directory to path.
+        # The project directory has precedence over system modules,
+        # so we prepend it to the path.
+        sys.path.prepend(os.getcwd())
 
         self._settings = symbol_by_name('django.conf:settings')
         self.app.loader.now = self.now

{"golden_diff": "diff --git a/celery/fixups/django.py b/celery/fixups/django.py\n--- a/celery/fixups/django.py\n+++ b/celery/fixups/django.py\n@@ -57,8 +57,10 @@\n         self._worker_fixup = None\n \n     def install(self):\n-        # Need to add project directory to path\n-        sys.path.append(os.getcwd())\n+        # Need to add project directory to path.\n+        # The project directory has precedence over system modules,\n+        # so we prepend it to the path.\n+        sys.path.prepend(os.getcwd())\n \n         self._settings = symbol_by_name('django.conf:settings')\n         self.app.loader.now = self.now\n", "issue": "Django fixup appends to PYTHONPATH instead of prepending\nHi,\r\n\r\n## Environment & Settings\r\n**Celery version**: 4.2.1  (windowlicker)\r\n\r\n# Steps to Reproduce\r\n\r\nWe are using Celery + Django in [dissemin](https://github.com/dissemin/dissemin/). We have a Django app named \"statistics\" which is actually a name conflicting with a Python 3 package from standard library. This should be fine in principle as long as the `PYTHONPATH` is set so that the local modules have precedence over the system ones.\r\n\r\nWhen running Celery CLI, the system wide module has precedence over the local ones apparently.\r\n\r\nI traced this issue back to [this `sys.path` tweak](https://github.com/celery/celery/blob/072dab85261599234341cc714b0d6f0caca20f00/celery/fixups/django.py#L60-L61), which is actually **appending** local path instead of prepending it.\r\n\r\nI may have missed something, but is it important for some reason to append it and not prepend it in this context?\r\n\r\n# Expected Behavior\r\n\r\nCelery should load the local module as expected.\r\n\r\n# Actual Behavior\r\n\r\n```\r\n# When going through celery CLI\r\nsys.path == ['/Users/lverney/.local/share/virtualenvs/dissemin3/bin', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python36.zip', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6/site-packages', '/Users/lverney/.local/share/virtualenvs/dissemin3/src/django-allauth', '/Users/lverney/tmp/dissemin']\r\n\r\n# Without celery\r\nsys.path == ['', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python36.zip', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/Users/lverney/.local/share/virtualenvs/dissemin3/lib/python3.6/site-packages', '/Users/lverney/.local/share/virtualenvs/dissemin3/src/django-allauth']\r\n```\r\n\r\nWe can see that current path is actually appended, not prepended. Therefore, \"system\" modules have precedence on the ones from the local project.\r\n\r\n\r\n# Workaround\r\n\r\nFor people experiencing this issue, `PYTHONPATH=$(pwd) celery \u2026` is a workaround.\r\n\r\n\r\nBest,\r\n\r\n/cc @wetneb who first noticed this issue.\n", "before_files": [{"content": "\"\"\"Django-specific customization.\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nimport sys\nimport warnings\nfrom datetime import datetime\nfrom importlib import import_module\n\nfrom kombu.utils.imports import symbol_by_name\nfrom kombu.utils.objects import cached_property\n\nfrom celery import _state, signals\nfrom celery.exceptions import FixupWarning, ImproperlyConfigured\n\n__all__ = ('DjangoFixup', 'fixup')\n\nERR_NOT_INSTALLED = \"\"\"\\\nEnvironment variable DJANGO_SETTINGS_MODULE is defined\nbut Django isn't installed.  Won't apply Django fix-ups!\n\"\"\"\n\n\ndef _maybe_close_fd(fh):\n    try:\n        os.close(fh.fileno())\n    except (AttributeError, OSError, TypeError):\n        # TypeError added for celery#962\n        pass\n\n\ndef _verify_django_version(django):\n    if django.VERSION < (1, 11):\n        raise ImproperlyConfigured('Celery 4.x requires Django 1.11 or later.')\n\n\ndef fixup(app, env='DJANGO_SETTINGS_MODULE'):\n    \"\"\"Install Django fixup if settings module environment is set.\"\"\"\n    SETTINGS_MODULE = os.environ.get(env)\n    if SETTINGS_MODULE and 'django' not in app.loader_cls.lower():\n        try:\n            import django  # noqa\n        except ImportError:\n            warnings.warn(FixupWarning(ERR_NOT_INSTALLED))\n        else:\n            _verify_django_version(django)\n            return DjangoFixup(app).install()\n\n\nclass DjangoFixup(object):\n    \"\"\"Fixup installed when using Django.\"\"\"\n\n    def __init__(self, app):\n        self.app = app\n        if _state.default_app is None:\n            self.app.set_default()\n        self._worker_fixup = None\n\n    def install(self):\n        # Need to add project directory to path\n        sys.path.append(os.getcwd())\n\n        self._settings = symbol_by_name('django.conf:settings')\n        self.app.loader.now = self.now\n\n        signals.import_modules.connect(self.on_import_modules)\n        signals.worker_init.connect(self.on_worker_init)\n        return self\n\n    @property\n    def worker_fixup(self):\n        if self._worker_fixup is None:\n            self._worker_fixup = DjangoWorkerFixup(self.app)\n        return self._worker_fixup\n\n    @worker_fixup.setter\n    def worker_fixup(self, value):\n        self._worker_fixup = value\n\n    def on_import_modules(self, **kwargs):\n        # call django.setup() before task modules are imported\n        self.worker_fixup.validate_models()\n\n    def on_worker_init(self, **kwargs):\n        self.worker_fixup.install()\n\n    def now(self, utc=False):\n        return datetime.utcnow() if utc else self._now()\n\n    def autodiscover_tasks(self):\n        from django.apps import apps\n        return [config.name for config in apps.get_app_configs()]\n\n    @cached_property\n    def _now(self):\n        return symbol_by_name('django.utils.timezone:now')\n\n\nclass DjangoWorkerFixup(object):\n    _db_recycles = 0\n\n    def __init__(self, app):\n        self.app = app\n        self.db_reuse_max = self.app.conf.get('CELERY_DB_REUSE_MAX', None)\n        self._db = import_module('django.db')\n        self._cache = import_module('django.core.cache')\n        self._settings = symbol_by_name('django.conf:settings')\n\n        self.interface_errors = (\n            symbol_by_name('django.db.utils.InterfaceError'),\n        )\n        self.DatabaseError = symbol_by_name('django.db:DatabaseError')\n\n    def django_setup(self):\n        import django\n        django.setup()\n\n    def validate_models(self):\n        from django.core.checks import run_checks\n        self.django_setup()\n        run_checks()\n\n    def install(self):\n        signals.beat_embedded_init.connect(self.close_database)\n        signals.worker_ready.connect(self.on_worker_ready)\n        signals.task_prerun.connect(self.on_task_prerun)\n        signals.task_postrun.connect(self.on_task_postrun)\n        signals.worker_process_init.connect(self.on_worker_process_init)\n        self.close_database()\n        self.close_cache()\n        return self\n\n    def on_worker_process_init(self, **kwargs):\n        # Child process must validate models again if on Windows,\n        # or if they were started using execv.\n        if os.environ.get('FORKED_BY_MULTIPROCESSING'):\n            self.validate_models()\n\n        # close connections:\n        # the parent process may have established these,\n        # so need to close them.\n\n        # calling db.close() on some DB connections will cause\n        # the inherited DB conn to also get broken in the parent\n        # process so we need to remove it without triggering any\n        # network IO that close() might cause.\n        for c in self._db.connections.all():\n            if c and c.connection:\n                self._maybe_close_db_fd(c.connection)\n\n        # use the _ version to avoid DB_REUSE preventing the conn.close() call\n        self._close_database()\n        self.close_cache()\n\n    def _maybe_close_db_fd(self, fd):\n        try:\n            _maybe_close_fd(fd)\n        except self.interface_errors:\n            pass\n\n    def on_task_prerun(self, sender, **kwargs):\n        \"\"\"Called before every task.\"\"\"\n        if not getattr(sender.request, 'is_eager', False):\n            self.close_database()\n\n    def on_task_postrun(self, sender, **kwargs):\n        # See https://groups.google.com/group/django-users/\n        #            browse_thread/thread/78200863d0c07c6d/\n        if not getattr(sender.request, 'is_eager', False):\n            self.close_database()\n            self.close_cache()\n\n    def close_database(self, **kwargs):\n        if not self.db_reuse_max:\n            return self._close_database()\n        if self._db_recycles >= self.db_reuse_max * 2:\n            self._db_recycles = 0\n            self._close_database()\n        self._db_recycles += 1\n\n    def _close_database(self):\n        for conn in self._db.connections.all():\n            try:\n                conn.close_if_unusable_or_obsolete()\n            except self.interface_errors:\n                pass\n            except self.DatabaseError as exc:\n                str_exc = str(exc)\n                if 'closed' not in str_exc and 'not connected' not in str_exc:\n                    raise\n\n    def close_cache(self):\n        try:\n            self._cache.close_caches()\n        except (TypeError, AttributeError):\n            pass\n\n    def on_worker_ready(self, **kwargs):\n        if self._settings.DEBUG:\n            warnings.warn('Using settings.DEBUG leads to a memory leak, never '\n                          'use this setting in production environments!')\n", "path": "celery/fixups/django.py"}], "after_files": [{"content": "\"\"\"Django-specific customization.\"\"\"\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nimport sys\nimport warnings\nfrom datetime import datetime\nfrom importlib import import_module\n\nfrom kombu.utils.imports import symbol_by_name\nfrom kombu.utils.objects import cached_property\n\nfrom celery import _state, signals\nfrom celery.exceptions import FixupWarning, ImproperlyConfigured\n\n__all__ = ('DjangoFixup', 'fixup')\n\nERR_NOT_INSTALLED = \"\"\"\\\nEnvironment variable DJANGO_SETTINGS_MODULE is defined\nbut Django isn't installed.  Won't apply Django fix-ups!\n\"\"\"\n\n\ndef _maybe_close_fd(fh):\n    try:\n        os.close(fh.fileno())\n    except (AttributeError, OSError, TypeError):\n        # TypeError added for celery#962\n        pass\n\n\ndef _verify_django_version(django):\n    if django.VERSION < (1, 11):\n        raise ImproperlyConfigured('Celery 4.x requires Django 1.11 or later.')\n\n\ndef fixup(app, env='DJANGO_SETTINGS_MODULE'):\n    \"\"\"Install Django fixup if settings module environment is set.\"\"\"\n    SETTINGS_MODULE = os.environ.get(env)\n    if SETTINGS_MODULE and 'django' not in app.loader_cls.lower():\n        try:\n            import django  # noqa\n        except ImportError:\n            warnings.warn(FixupWarning(ERR_NOT_INSTALLED))\n        else:\n            _verify_django_version(django)\n            return DjangoFixup(app).install()\n\n\nclass DjangoFixup(object):\n    \"\"\"Fixup installed when using Django.\"\"\"\n\n    def __init__(self, app):\n        self.app = app\n        if _state.default_app is None:\n            self.app.set_default()\n        self._worker_fixup = None\n\n    def install(self):\n        # Need to add project directory to path.\n        # The project directory has precedence over system modules,\n        # so we prepend it to the path.\n        sys.path.prepend(os.getcwd())\n\n        self._settings = symbol_by_name('django.conf:settings')\n        self.app.loader.now = self.now\n\n        signals.import_modules.connect(self.on_import_modules)\n        signals.worker_init.connect(self.on_worker_init)\n        return self\n\n    @property\n    def worker_fixup(self):\n        if self._worker_fixup is None:\n            self._worker_fixup = DjangoWorkerFixup(self.app)\n        return self._worker_fixup\n\n    @worker_fixup.setter\n    def worker_fixup(self, value):\n        self._worker_fixup = value\n\n    def on_import_modules(self, **kwargs):\n        # call django.setup() before task modules are imported\n        self.worker_fixup.validate_models()\n\n    def on_worker_init(self, **kwargs):\n        self.worker_fixup.install()\n\n    def now(self, utc=False):\n        return datetime.utcnow() if utc else self._now()\n\n    def autodiscover_tasks(self):\n        from django.apps import apps\n        return [config.name for config in apps.get_app_configs()]\n\n    @cached_property\n    def _now(self):\n        return symbol_by_name('django.utils.timezone:now')\n\n\nclass DjangoWorkerFixup(object):\n    _db_recycles = 0\n\n    def __init__(self, app):\n        self.app = app\n        self.db_reuse_max = self.app.conf.get('CELERY_DB_REUSE_MAX', None)\n        self._db = import_module('django.db')\n        self._cache = import_module('django.core.cache')\n        self._settings = symbol_by_name('django.conf:settings')\n\n        self.interface_errors = (\n            symbol_by_name('django.db.utils.InterfaceError'),\n        )\n        self.DatabaseError = symbol_by_name('django.db:DatabaseError')\n\n    def django_setup(self):\n        import django\n        django.setup()\n\n    def validate_models(self):\n        from django.core.checks import run_checks\n        self.django_setup()\n        run_checks()\n\n    def install(self):\n        signals.beat_embedded_init.connect(self.close_database)\n        signals.worker_ready.connect(self.on_worker_ready)\n        signals.task_prerun.connect(self.on_task_prerun)\n        signals.task_postrun.connect(self.on_task_postrun)\n        signals.worker_process_init.connect(self.on_worker_process_init)\n        self.close_database()\n        self.close_cache()\n        return self\n\n    def on_worker_process_init(self, **kwargs):\n        # Child process must validate models again if on Windows,\n        # or if they were started using execv.\n        if os.environ.get('FORKED_BY_MULTIPROCESSING'):\n            self.validate_models()\n\n        # close connections:\n        # the parent process may have established these,\n        # so need to close them.\n\n        # calling db.close() on some DB connections will cause\n        # the inherited DB conn to also get broken in the parent\n        # process so we need to remove it without triggering any\n        # network IO that close() might cause.\n        for c in self._db.connections.all():\n            if c and c.connection:\n                self._maybe_close_db_fd(c.connection)\n\n        # use the _ version to avoid DB_REUSE preventing the conn.close() call\n        self._close_database()\n        self.close_cache()\n\n    def _maybe_close_db_fd(self, fd):\n        try:\n            _maybe_close_fd(fd)\n        except self.interface_errors:\n            pass\n\n    def on_task_prerun(self, sender, **kwargs):\n        \"\"\"Called before every task.\"\"\"\n        if not getattr(sender.request, 'is_eager', False):\n            self.close_database()\n\n    def on_task_postrun(self, sender, **kwargs):\n        # See https://groups.google.com/group/django-users/\n        #            browse_thread/thread/78200863d0c07c6d/\n        if not getattr(sender.request, 'is_eager', False):\n            self.close_database()\n            self.close_cache()\n\n    def close_database(self, **kwargs):\n        if not self.db_reuse_max:\n            return self._close_database()\n        if self._db_recycles >= self.db_reuse_max * 2:\n            self._db_recycles = 0\n            self._close_database()\n        self._db_recycles += 1\n\n    def _close_database(self):\n        for conn in self._db.connections.all():\n            try:\n                conn.close_if_unusable_or_obsolete()\n            except self.interface_errors:\n                pass\n            except self.DatabaseError as exc:\n                str_exc = str(exc)\n                if 'closed' not in str_exc and 'not connected' not in str_exc:\n                    raise\n\n    def close_cache(self):\n        try:\n            self._cache.close_caches()\n        except (TypeError, AttributeError):\n            pass\n\n    def on_worker_ready(self, **kwargs):\n        if self._settings.DEBUG:\n            warnings.warn('Using settings.DEBUG leads to a memory leak, never '\n                          'use this setting in production environments!')\n", "path": "celery/fixups/django.py"}]}