6151

How to have eve write to different databases based on various URL parameters and request values?

Question:

I'm attempting to create a REST API that selects the appropriate mongo database to write to along with the correct collection. How do I have eve select the database with the same name as a parameter as well as the collection?

Answer1:

With upcoming v0.6 Eve will natively support multiple Mongo instances.

<blockquote>

New: Support for multiple MongoDB databases and/or servers.

</blockquote>

You can have individual API endpoints served by different Mongo instances:

<blockquote>

mongo_prefix resource setting allows overriding of the default MONGO prefix used when retrieving MongoDB settings from configuration. For example, set a resource mongo_prefix to MONGO2 to read/write from the database configured with that prefix in your settings file (MONGO2_HOST, MONGO2_DBNAME, etc.)

</blockquote>

And/or you can use a different Mongo instance depending on the user hitting the database:

<blockquote>

set_mongo_prefix() and get_mongo_prefix() have been added to <strong>BasicAuth</strong> class and derivates. These can be used to arbitrarily set the target database depending on the token/client performing the request.

</blockquote>

A (very) naive implementation of user instances, taken from the <a href="http://python-eve.org/authentication.html#authdrivendb" rel="nofollow">docs</a>:

from eve.auth import BasicAuth class MyBasicAuth(BasicAuth): def check_auth(self, username, password, allowed_roles, resource, method): if username == 'user1': self.set_mongo_prefix('MONGO1') elif username == 'user2': self.set_mongo_prefix('MONGO2') else: # serve all other users from the default db. self.set_mongo_prefix(None) return username is not None and password == 'secret' app = Eve(auth=MyBasicAuth) app.run()

Also:

<blockquote>

Database connections are cached in order to not to loose performance. Also, this change only affects the MongoDB engine, so extensions currently targeting other databases should not need updates (they will not inherit this feature however.)

</blockquote>

Hope this will cover your needs. It's currently on the <a href="https://github.com/nicolaiarocci/eve" rel="nofollow">development</a> branch so you can already experiment/play with it.

Answer2:

Say you have parameters "dbname" and "collectionname", and a global MongoClient instance named "client":

collection = client[dbname][collectionname]

PyMongo's client supports the "[]" syntax for getting a database with a given name, and PyMongo's database supports "[]" for getting a collection.

Here's a more complete example with Flask:

client = MongoClient() @app.route('/<dbname>/<collection_name>') def find_something(dbname, collection_name): return client[dbname][collection_name].find_one()

The good thing about my example is it reuses one MongoClient throughout, so you get optimal performance and connection pooling. The bad thing, of course, is you allow your users to access any database and any collection, so you'd want to secure that somehow.

Recommend

  • Cannot debug project after upgrading to Service Fabric SDK v2.3.301
  • CouchDB views erroring out
  • GMP Bit shift doesn't work on negative numbers
  • Date api for managing off days in an year?
  • PHP OOXML Libraries? [closed]
  • IE readonly textarea problem
  • How to distribute Java-based software?
  • how to load css classes from my own project specfic css in Sitecore's RAD editor?
  • Using multiple input pipelines in TensorFlow
  • How to fallback to entirely different index page if user has javascript disable?
  • PHP: Very simple Encode/Decode string
  • How to know if a JFrame is on screen in a multi screen environment
  • Mockery and Laravel constructor injection
  • Swift iOS don't recognize GCM library imports?
  • Are there “Dynamic Playlists” of unit tests in Visual Studio?
  • Cordova Apache wrong module path
  • How do you keep a running instance for Google App Engine
  • ASPNetCore MVC Routing Let Server Handle Specific Route
  • Activation Function choice for Neural network
  • Prevent Tomcat from caching request during starup
  • jQuery ready not fired after rails link_to is clicked
  • Refering to the class itself from within a class mehod in Objective C
  • Yii2: Config params vs. const/define
  • Exception “firebase.functions() takes … no argument …” when specifying a region for a Cloud Function
  • Algorithm for a smudge tool?
  • Highlight one bar in a series in highcharts?
  • Javascript simulate pressing enter in input box
  • Why winpcap requires both .lib and .dll to run?
  • Calling of Constructors in a Java
  • Run Powershell script from inside other Powershell script with dynamic redirection to file
  • PHP: When would you need the self:: keyword?
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Load html files in TinyMce
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • coudnt use logback because of log4j
  • Turn off referential integrity in Derby? is it possible?
  • Authorize attributes not working in MVC 4
  • Busy indicator not showing up in wpf window [duplicate]
  • Python/Django TangoWithDjango Models and Databases
  • Net Present Value in Excel for Grouped Recurring CF