具有用户分辨率和过滤功能的Flask式终端

2024-04-26 03:02:51 发布

您现在位置:Python中文网/ 问答频道 /正文

对于只返回属于请求它们的用户的对象的API,应该如何正确地进行查找?在

api/version/items/<items_id>

或者

^{pr2}$

在第一种情况下,服务器使用用户id查询数据库,用户id是通过身份验证获得的。在

我不知道怎么在烧瓶里创造两种情况。我认为一个预处理器会很有用,我可以从授权(JWT token)中获取user_id,但是我找不到一种方法来使用它作为DB的搜索参数。在

from flask_jwt import JWT, jwt_required, current_user
...
manager.create_api(Item,
               methods=['GET'],
               collection_name='items',
               url_prefix='/api',
               preprocessors=dict(GET_SINGLE=[api_auth],GET_MANY=[api_auth]))   


@jwt_required()
def api_auth(*args, **kwargs):
    user_id = current_user.id
    # some code with user id addition.
    pass

Tags: 对象用户authapiidgetversionrequired
2条回答

您应该使用一个直接引用要查询的资源的端点。例如:

api/version/items

您应该分别定义get_single和{}预处理器。单个(整数)的instance_id和多个预处理器的result参数(字典)应用于定义返回给用户的内容。在

Flask-restless docs

Those preprocessors and postprocessors that accept dictionaries as parameters can (and should) modify their arguments in-place. That means the changes made to, for example, the result dictionary will be seen by the Flask-Restless view functions and ultimately returned to the client.

因此,在预处理程序中,可以执行以下操作来检索数据库中的项(在与用户的关系中定义):

^{pr2}$

预处理器将是您构建查询对象的地方。我认为项目的端点应该简单地如下所示:

api/version/items

将传递一个whithin请求,但会传递一个查询:

^{pr2}$

相关问题 更多 >

    热门问题