title: Django - Share a RabbitMQ Connection between All Processes that apache creates per request?
body: <p>My stack is <em>Django 1.3(Python 2.7)</em> + <em>Apache</em> + mod_wsgi </p>
  
  <p><em>Apache</em> spawns a new process per request... Sometimes in those requests I have to <em>Publish</em> a message to <em>RabbitMQ</em> about some heavy task to be done later (like notifying someone's followers about a cat photo they just posted).</p>
  
  <p><em>Publishing</em> involves making connection to <em>RabbitMQ</em>, which is expensive. (see this SO question: <a href="https://stackoverflow.com/questions/11147065/rabbitmq-create-connection-is-an-expensive-operation">RabbitMQ create connection is an expensive operation</a>)</p>
  
  <p>I am also sadly aware of Python's incapability to share memory across processes... sigh :(</p>
  
  <p>How in this case, do I prevent the overhead of creating and closing a RabbitMQ connection per apache request?</p>
  
  <p>For Clarity, Using RabbitMQ + pika here is my failed attempt at sharing the connection between processes:</p>
  
  <pre><code>def test_view(request):
      """a django view publishing to RabbitMQ"""
      connection = Connection.get_shared_connection()
      channel = connection.channel() 
      channel.queue_declare(queue='test_queue', auto_delete=False, durable=True)
      channel.basic_publish(exchange='', routing_key='test_queue', body='Hello Rabbit!', 
                                  properties=pika.BasicProperties(delivery_mode=2))
      print 'SENT:', body
  
      return HttpResponse("published")
  
  
  class Connection(object):
      """failed attempt to create a singleton"""
      _connection = None
  
      @staticmethod
      def get_shared_connection(): # return a pika connection
          if not Connection._connection:
              print 'NEW CONNECTION'  # prints NEW CONNECTION with every request
              Connection._connection = pika.BlockingConnection(pika.ConnectionParameters(
                                                                             host='localhost'))
          return Connection._connection
  </code></pre>
  
  <p>In server setting (<em>Django</em> + <em>Apache</em> + mod_wsgi) <code>'NEW CONNECTION'</code> is printed with every request made to <code>test_view</code></p>
  
  <p>It seems like an issue anybody would run into using Django with RabbitMQ. There has to be a way...</p>
  
  <p>Thanks... any help is appreciated</p>