Python eve - 用户限制资源访问功能,项目的 ID_FIELD 为 AUTH_FIELD

标签 python eve

我有一组用户,我在没有 POST 身份验证的情况下将其打开,以便用户可以创建帐户,现在我想限制测试集合的访问权限,用户只能创建一个测试文档,我添加了 auth_field到user_id,我想添加以user_id作为field_id的文档,同时将其用作auth_field,进行读/写限制。

这是我的测试模型,我添加了 PUT,因为用户有自己的 ID,应该将其用作 test_item id_field。

当我尝试用这个运行 Eve 时,出现了一个异常,有没有办法正确执行此操作,以便每个经过正确身份验证且 auth_field 设置为 user_id 的用户请求都将透明地工作?

感谢您的帮助。

tests = {
    'resource_methods': ['GET'],
    'upsert_on_put': True,
    'id_field': 'test_id'
    'item_title': 'test',
    'auth_field': 'test_id',
    'item_methods': ['GET', 'PATCH', 'PUT'],
    'schema': {
        'test_field': {
            'type': 'string',
            'required': True
        }
    }
}

异常(exception):

eve.exceptions.ConfigException: "tests": auth_field cannot be set to id_field (test_id)

TL;DR

与用户和测试集合建立一对一的关系,每个用户有一个测试,身份验证后通过 auth_field 透明地工作。

最佳答案

您可以使用 before insert event hook 来执行此 1:1 关系,如果您正在使用您提到的用户限制资源访问。因为这样你的文档上就会有一个 auth_field 。在我的示例中,auth 字段是 user_id

你的on_insert_tests钩子(Hook)会像这样

from flask import current_app, abort

def check_inserted(documents):
    # get ID for current user
    user_id = current_app.auth.get_request_auth_value()
    # find tests for the current user
    collection = current_app.data.driver.db['tests']
    tests = collection.find({'user_id': user_id})

    if tests.count() > 0:
        abort(409, 'Test already present for this account. Only one allowed.')

因此,当为当前用户插入第二个测试时,它将中止。

顺便说一句,我不明白为什么您要将测试中的 ID 字段更改为 test_id,而不是使用默认的 _id

关于Python eve - 用户限制资源访问功能,项目的 ID_FIELD 为 AUTH_FIELD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35457787/

相关文章:

Python:为什么我得到 [Errno 13] Permission Denied?

python - 使用整数作为 _id 类型为 item_lookup 返回 HTTP 400

eve - 请求嵌入对象列表

python - 使用 Python Eve 组织 REST API Web 服务构建

python - 如何在自定义EVE route 编写模型

python - REST API 框架适用于我的 python 程序而不是数据库

python - 使用 Tornado 通过 GET 处理所有 REST 请求

python - Python 中不常见功能级别的一种热门编码

python - 推广 PyQt 小部件

python - 对 Sklearn Pipeline 和 Feature Union 的困惑