title: Multi-tenant Django applications using Mongoengine
body: <p>I want to build a multi tenant architecture for a SAAS system. We are using Django as our backend and mongoengine as our main database and gunicorn as our web-server.</p>
  
  <p>Our clients are a few big companies, so the number of databases pre-allocating space shouldn't be a problem.</p>
  
  <p>The first approach we took was to write a middleware to determine the source of the request to properly connect to a mongoengine database. Here is the code:</p>
  
  <pre><code>class MongoConnectionMiddleware(object):
    def process_request(self, request):
      if request.user.is_authenticated():
        mongo_connect(request.user.profile.establishment)
  </code></pre>
  
  <p>And the mongo_connect method:</p>
  
  <pre><code>def mongo_connect(establishment):
    db_name = 'db_client_%d' % establishment.id
    connect(db_name)
  </code></pre>
  
  <p>This will register the "default" alias as the db_name for every mongoengine request.</p>
  
  <p>But it seems that when many concurrent users from different companies are making requests, each one sets the default db_name to it's own name.</p>
  
  <p>As an example:
  Company A makes a request and connects to database A. While A is making it's work company B connects to database B. This makes A also connect to B's database in the process, so A fails to find some ids.</p>
  
  <p>¿Is there a way to isolate the connection to the mongo database per request to avoid this problem?</p>