夏娃如何基于各种URL参数和请求值写入不同的数据库? [英] How to have eve write to different databases based on various URL parameters and request values?

查看:114
本文介绍了夏娃如何基于各种URL参数和请求值写入不同的数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个REST API,以选择要写入的适当的mongo数据库以及正确的集合.我该如何选择与参数和集合同名的数据库?

I'm attempting to create a REST API that selects the appropriate mongo database to write to along with the correct collection. How do I have eve select the database with the same name as a parameter as well as the collection?

推荐答案

在即将发布的v0.6版本中,Eve本身将支持多个Mongo实例.

With upcoming v0.6 Eve will natively support multiple Mongo instances.

新功能:支持多个MongoDB数据库和/或服务器.

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

您可以将不同的Mongo实例提供单独的API端点:

You can have individual API endpoints served by different Mongo instances:

mongo_prefix资源设置允许覆盖从配置中检索MongoDB设置时使用的默认MONGO前缀.例如,将资源mongo_prefix设置为MONGO2,以便从在设置文件(MONGO2_HOST,MONGO2_DBNAME等)中配置了该前缀的数据库中进行读写.

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实例:

And/or you can use a different Mongo instance depending on the user hitting the database:

set_mongo_prefix()get_mongo_prefix()已添加到 BasicAuth 类并派生.这些可以用于根据执行请求的令牌/客户端任意设置目标数据库.

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.

一个非常简单的用户实例实现,取自文档:

A (very) naive implementation of user instances, taken from the 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()

也:

数据库连接被缓存,以免降低性能.而且,此更改仅影响MongoDB引擎,因此当前针对其他数据库的扩展不需要更新(但是它们不会继承此功能.)

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 分支上,因此您已经可以对其进行实验/播放.

Hope this will cover your needs. It's currently on the development branch so you can already experiment/play with it.

这篇关于夏娃如何基于各种URL参数和请求值写入不同的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆