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?
How to have eve write to different databases based on various URL parameters and request values?
1.4k views Asked by Garrett M At
2
There are 2 answers
2
On
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.
With upcoming v0.6 Eve will natively support multiple Mongo instances.
You can have individual API endpoints served by different Mongo instances:
And/or you can use a different Mongo instance depending on the user hitting the database:
A (very) naive implementation of user instances, taken from the docs:
Also:
Hope this will cover your needs. It's currently on the
development
branch so you can already experiment/play with it.