From b9c88c78827b848bdfaa5310f7c08b66437124fe Mon Sep 17 00:00:00 2001
From: Sebastian Noack <sebastian.noack@gmail.com>
Date: Fri, 12 Oct 2012 10:00:16 +0200
Subject: [PATCH] Re-connect database and memcached after fork.

---
 django/core/cache/backends/memcached.py |    5 +++++
 django/db/backends/__init__.py          |   10 ++++++++++
 2 files changed, 15 insertions(+)

diff --git a/django/core/cache/backends/memcached.py b/django/core/cache/backends/memcached.py
index 9bb47c8..b8e3fa7 100644
--- a/django/core/cache/backends/memcached.py
+++ b/django/core/cache/backends/memcached.py
@@ -2,6 +2,7 @@
 
 import time
 from threading import local
+from multiprocessing.util import register_after_fork
 
 from django.core.cache.backends.base import BaseCache, InvalidCacheBackendError
 
@@ -25,6 +26,10 @@ class BaseMemcachedCache(BaseCache):
         self._lib = library
         self._options = params.get('OPTIONS', None)
 
+        def _after_fork(cache):
+            cache._client = None
+        register_after_fork(self, _after_fork)
+
     @property
     def _cache(self):
         """
diff --git a/django/db/backends/__init__.py b/django/db/backends/__init__.py
index 02d2a16..e84ca61 100644
--- a/django/db/backends/__init__.py
+++ b/django/db/backends/__init__.py
@@ -4,6 +4,7 @@ try:
     from django.utils.six.moves import _thread as thread
 except ImportError:
     from django.utils.six.moves import _dummy_thread as thread
+from multiprocessing.util import register_after_fork
 from contextlib import contextmanager
 
 from django.conf import settings
@@ -41,6 +42,15 @@ class BaseDatabaseWrapper(object):
         self._thread_ident = thread.get_ident()
         self.allow_thread_sharing = allow_thread_sharing
 
+        def _after_fork(connection):
+            connection.close()
+
+            connection.transaction_state = []
+            connection.savepoint_state = 0
+            connection._dirty = None
+            connection._thread_ident = thread.get_ident()
+        register_after_fork(self, _after_fork)
+
     def __eq__(self, other):
         return self.alias == other.alias
 
-- 
1.7.10.4

