我正在尝试创建一个REST API,以选择要写入的适当的mongo数据库以及正确的集合.我如何选择与参数同名的数据库以及集合?
解决方法:
Eve即将推出v0.6版本,它将在本地支持多个Mongo实例.
New: Support for multiple MongoDB databases and/or servers.
您可以将不同的Mongo实例提供单独的API端点:
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.)
和/或您可以根据用户访问数据库的情况使用其他Mongo实例:
set_mongo_prefix()
andget_mongo_prefix()
have been added to BasicAuth class and derivates. These can be used to arbitrarily set the target database depending on the token/client performing the request.
一个(非常)天真的用户实例实现,取自docs:
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()
也:
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.)
希望这能满足您的需求.它目前在development
分支上,因此您已经可以尝试/玩它.