【问题标题】:How to access nested resources in Flask-Classy?如何访问 Flask-Classy 中的嵌套资源?
【发布时间】:2015-02-17 23:39:53
【问题描述】:

我一直在为我的服务器使用 Flask-Classy,它运行良好。但是,我遇到了一个我没有见过的用例,但这是一个非常常见的用例,所以如果不可能的话,我会感到震惊。

我有两个要嵌套的 API,我的意思是我有:

class UsersView(FlaskView):
    decorators = [jwt_required()]
    route_prefix = '/api/v1/'

    def index(self):
    ...

位于http://example.com/api/v1/users,我可以通过http://example.com/api/v1/users/1访问用户1

现在,我将如何编写 FlaskView 让我做这样的事情? http://example.com/api/v1/users/1/devices/3

当我尝试在 route_prefix 中嵌入资源 id 时,我得到一个关键字参数错误:

class DevicesView(FlaskView):
    decorators = [jwt_required()]
    route_prefix = '/api/v1/users/<user_id>/'

    def index(self):
    ...

TypeError: index() 得到了一个意外的关键字参数 'user_id'

最后一点是,我自然可以使用 kwargs:

route_prefix = '/api/v1/users/<user_id>/'

def test(self, **kwargs):
    print kwargs['user_id']

http://example.com/api/v1/users/103/devices 会吐出 '103',但是,使用 kwargs 感觉有点做作。有没有更好的办法?

【问题讨论】:

    标签: python rest flask crud flask-restful


    【解决方案1】:

    我将顶级占位符放在 register 调用中的 route_base 中。

    例如:

    class UsersView(FlaskView):
        @route('/', methods=['GET'])
        def index(self):
            pass
    
    class DevicesView(FlaskView):
        @route('/', methods=['GET'])
        def index(self, user_id):
            pass
    
    UsersView.register(app, route_base='/users', trailing_slash=False)
    DevicesView.register(app, route_base='/users/<user_id>/devices', trailing_slash=False)
    

    现在 user_id 作为 DevicesView 中每个方法的第一个参数。

    【讨论】:

      【解决方案2】:

      如果您还没有找到解决方案...答案很简单,您需要将索引定义为:

      def index(self, user_id):

      您必须这样做,因为您想知道通过它访问所需资源的基本资源。在您的示例中,设备索引将为我提供属于该用户的所有设备的列表。为了获得此信息,您首先需要知道正在询问哪些用户的设备

      【讨论】:

      • 感谢您的回复。你试过这个并让它工作吗?我以前试过这个,它抛出一个“ValueError:变量名'user_id'使用了两次。”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-25
      相关资源
      最近更新 更多