如何让 eve 根据各种 URL 参数和请求值写入不同的数据库?

How to have eve write to different databases based on various URL parameters and request values?

我正在尝试创建一个 REST API,select 是要写入的适当 mongo 数据库以及正确的集合。如何让 select 与参数同名的数据库以及集合?

假设您有参数 "dbname" 和 "collectionname",以及一个名为 "client":

的全局 MongoClient 实例
collection = client[dbname][collectionname]

PyMongo 客户端支持“[]”语法获取指定名称的数据库,PyMongo 数据库支持“[]”获取集合。

这是一个更完整的 Flask 示例:

client = MongoClient()

@app.route('/<dbname>/<collection_name>')
def find_something(dbname, collection_name):
    return client[dbname][collection_name].find_one()

我的示例的优点在于它始终重复使用一个 MongoClient,因此您可以获得最佳性能和连接池。当然,坏处是您允许您的用户访问任何数据库和任何集合,因此您希望以某种方式保护它们。

随着即将推出的 v0.6,Eve 将原生支持多个 Mongo 实例。

New: Support for multiple MongoDB databases and/or servers.

您可以让单独的 API 端点由不同的 Mongo 实例提供服务:

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

And/or 您可以根据访问数据库的用户使用不同的 Mongo 实例:

set_mongo_prefix() and get_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 分支上,因此您已经可以 experiment/play 使用它了。