问题
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?
回答1:
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.
回答2:
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')
来源:https://stackoverflow.com/questions/49354474/can-i-dynamically-create-db-instances-for-use-with-mongo-prefix