python - 使用 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 返回到其父键的“父”键。两者都抛出错误,说我忘记指定值。我怎样才能让它工作?
解决方案
您必须添加资源名称。
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')
}
推荐阅读
- parsing - 这是将 EBNF 转换为 BNF 的有效方法吗?
- python - 使用 .loc 使用加号等于运算
- xampp - 无法在 xampp 上安装 Magento 2.4
- angular - angular2:为相同的路由和组件调用canDeactivate,但参数不同
- php - str_pad() 期望参数 1 是 PHP 中的字符串
- swift - 我怎样才能成功使用委托?按钮不适用于代表
- python - ImportError:无法导入名称'deprecated_endpoints'?
- html - 如何使用 SVG 路径从地图中获取坐标?
- java - 为什么我从 flink 得到重复的数据?
- python - 找到一个值的子集的最佳近似值