title: Python and mongoDB connection pool ( pymongo )
body: <p>I have a web application, and there are thousands of requests every minutes.
  the following is my python code for mongoDB connection:</p>
  
  <p>Tool.py:</p>
  
  <pre><code>globalconnection = None
  
  def getCollection(name,safe=False,readpref=ReadPreference.PRIMARY):
  
      global globalconnection
      while globalconnection is None:
              try:
                      if not globalconnection is None:
                              globalconnection.close()
                      globalconnection = Connection('mongodb://host:port',replicaSet='mysetname',safe=False,read_preference=ReadPreference.PRIMARY,network_timeout=30,max_pool_size=1024)
              except Exception as e:
                      globalconnection = None
  
      request_context.connection = globalconnection
  
      return request_context.connection["mydb"]["mycoll"]
  </code></pre>
  
  <p>web.py</p>
  
  <pre><code>@app.route("/test")
  def test():
      request_collection = getCollection("user")
      results = request_collection.find()
      for result in results:
          #do something...
          request_collection.save(result)
      request_collection.end_request()
  </code></pre>
  
  <p>One http request gets the connection through this function,</p>
  
  <p>and the http request calls end_request before the end of the request.</p>
  
  <p>But I found that there are many AutoReconnect errors and over 20000 connections in mongoDB while increasing requests.</p>
  
  <p>Do you have any suggestion?</p>