[英]Marshal URLs for hierarchical relationships with Flask-restful
I have problems getting the flask-restful marshal_with function to do what I want.我在让flask-restful marshal_with 函数做我想做的事情时遇到问题。 Basically I have 4 endpoints to access two hierarchical entities (parents and children).
基本上我有 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 resources:家长资源:
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 resources:子资源:
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
should return the URL to get all children of this parent for the 'children' key. parent_marshal_template
应返回 URL 以获取此父项的所有子项作为“子项”键。 child_marshal_template
should return the URL to it's parent for the 'parent' key. child_marshal_template
应该将 URL 返回到它的父项的“父”键。 Both throw errors that say that I forgot to specify values.两者都抛出错误,说我忘记指定值。 How can I make it work?
我怎样才能让它工作?
You have to add the resource name.您必须添加资源名称。
app.add_resource(Parent,"/parent",endpoint='parent-endpoint')
app.add_resource(Child,"/child",endpoint='child-endpoint')
Once you add this, you can use the Field.Url
function to point to the api 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')
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.