首页 > 解决方案 > 使用 Flask-restful 对层次关系进行编组 URL

问题描述

我无法让 flask-restful marshal_with 函数做我想做的事。基本上我有 4 个端点来访问两个分层实体(父母和孩子)。

class Parent(db.Model):
  name = db.Column(db.String, primary_key=True)
  children = db.relationship(Child)

class Child(db.Model):
  name = db.Column(db.String, primary_key=True)
  parent = db.Column(db.String, db.ForeignKey('parents.name'))

家长资源:

parent_marshal_template = {
  'name': fields.String,
  'children': fields.Url('children-endpoint', attribute='name')
}

class Parents(Resource):  # /parents
  @marshal_with(parent_marshal_template)
  def get(self):
    return list_of_parents

class Parent(Resource):  # /parents/<str:name> (parent-endpoint)
  @marshal_with(parent_marshal_template)
  def get(self, name):
    return single_parent_with_name

子资源:

child_marshal_template = {
  'name': fields.String,
  'parent': fields.Url('parent-endpoint', attribute='name')
}

class Children(Resource):  # /parents/<str:parent>/children (children-endpoint)
  @marshal_with(child_marshal_template)
  def get(self, parent):
    return list_of_children_of_parent

class Child(Resource):  # /parents/<str:parent>/children/<str:name>
  @marshal_with(child_marshal_template)
  def get(self, parent, name):
    return single_child_with_name

parent_marshal_template应该返回 URL 以获取该父级的所有子级以获取“children”键。child_marshal_template应该将 URL 返回到其父键的“父”键。两者都抛出错误,说我忘记指定值。我怎样才能让它工作?

标签: pythonflaskflask-restful

解决方案


您必须添加资源名称。

app.add_resource(Parent,"/parent",endpoint='parent-endpoint')
app.add_resource(Child,"/child",endpoint='child-endpoint')

添加后,您可以使用该Field.Url函数指向 api 端点。

parent_marshal_template = {
  'name': fields.String,
  'children': fields.Url('children-endpoint', attribute='name')
}

child_marshal_template = {
  'name': fields.String,
  'parent': fields.Url('parent-endpoint', attribute='name')
}

推荐阅读