mongo_prefix
looks ideally designed for simple and effective data separation, it seems though you need to pre-define your available prefixes in settings.py. Is it possible to create a new prefix dynamically - for example to create a new instance per user on creation of that user?

- 6,606
- 1
- 20
- 33

- 51
- 5
2 Answers
The authentication base class has the set_mongo_prefix()
method that allows you to set the active db based on the current user. This snippet comes from the documentation:
Custom authentication classes can also set the database that should be used when serving the active request.
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('USER1_DB')
elif username == 'user2':
self.set_mongo_prefix('USER2_DB')
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()
The above is, of course, a trivial implementation, but can probably serve a useful starting point. See the above documentation link for the complete breakdown.

- 6,606
- 1
- 20
- 33
-
Thanks, I understand this and the example/documentation is clear - my question though was: is there a way for me to add a "USER3_DB", "USER4_DB" etc. as individual users are created during the execution part of the app lifecycle, or am I restricted to what I have declared in advance via settings.py at build time? – Dnsk Mar 19 '18 at 12:12
-
For each user created, you can use the username to build a dynamic prefix. If that's not the case, please clarify. – gcw Mar 19 '18 at 14:17
-
In the code snippet above, if the db USER1_DB doesn't exist, it will be created for you at the first write, if that's what you mean. – Nicola Iarocci Mar 19 '18 at 14:24
-
That's exactly what I meant, thanks very much. The documentation and examples imply the dbs must pre-exist. – Dnsk Mar 21 '18 at 09:38
Ultimately the answer to the question is that your prefixed database will be created for you with defaults if you have not first specified the matching values in your settings.py. In cases where you cannot put the values in settings.py (probably because you don't know them at the time) happily you can add them dynamically later; trivial example below.
def add_db_to_config(app, config_prefix='MONGO'):
def key(suffix):
return '%s_%s' % (config_prefix, suffix)
if key('DBNAME') in app.config:
return
app.config[key('HOST')] = app.config['MONGO_HOST']
app.config[key('PORT')] = app.config['MONGO_PORT']
app.config[key('DBNAME')] = key('DBNAME')
app.config[key('USERNAME')] = None
app.config[key('PASSWORD')] = None
and then later, e.g. in check_auth(...)
:
add_db_to_config(app, 'user_x_db')
self.set_mongo_prefix('user_x_db')

- 51
- 5