title: Flask + Mongo Multi-tenant app
body: <p>I am trying to build an app with multiple database for each client.
  With flask-mongoengine you can register multiple database connection and use the alias to connect to the database at the time of query ORM models. I am using <code>@before_request</code> hook to set the tenant. </p>
  
  <pre><code>app.config["MONGODB_SETTINGS"] = {
      'db': 'default',
      'host': 'mongodb://localhost/default',
      'alias': 'default'
  },
  {
      'db': 'client1',
      'host': 'mongodb://localhost/client1',
      'alias': 'client1'
  }
  
  from models.import Purchase
  def get_data():
      with switch_db(Purchase, g.context['tenant']) as Data:
          record = Data.objects(pk=&lt;id&gt;).first()
          return record
  </code></pre>
  
  <p>I am able to switch the database successfully with this approach. </p>
  
  <p>I want to switch the context of the database globally or at the time of user chooses client. So that I don't have to change it for each method and every time I have to query.</p>