-1

i have defined two mongo dbs using different mongo_db_prefixes like:

USER1_MONGO_DBNAME = 'user1db'
USER2_MONGO_DBNAME = 'user2db'

and remaining mongodb settings are same for both users.

if i want to change the mongodb name to be used for an eve app dynamically, how i can change?

Hari Krishnan
  • 2,049
  • 2
  • 18
  • 29
  • what do you mean `change dynamically` by api or other rule? – Brown Bear Aug 14 '18 at 12:49
  • Assume I have a python eve app running and this app serving some endpoints like employees. This endpoint is used to post and get data from mongodb. Suppose I will send a POST request with some json data for employees endpoint. Generally employees endpoint will use default mongodb collection "employees" for storing and fetching employees data from mongodb right. But my requirement is endpoint should store the posted data into the different mongodb collection based on the employee_type value like Private, Govt, Self which is present in the posted data. – Narendra Chennamsetty Aug 21 '18 at 05:30

1 Answers1

1

Take a look at this snippet from the documentation:

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()

This example is switching DB depending on the authenticated user. You could probably leverage the set_mongo_prefix method in your callback functions too, see Event Hooks.

Nicola Iarocci
  • 6,606
  • 1
  • 20
  • 33
  • How can we do this in a custom endpoint that we create? – Yash May 12 '22 at 11:56
  • 1
    @Yash You can use "g" which is available from flask.. you can import like ```from flask import g``` and then set ```g.mongo_prefix``` value. Internaly BasicAuth sets this same value – Yaset Arfat May 12 '22 at 12:15