[英]How to reuse the nested Resource methods in the encompassing Resource methods?
我有一个名为Profile
的资源,它嵌套了一个Port
资源列表,如下所示:
{
"profile": "abcd"
"ports": [
{
"port": "5687"
"state": "state"
"protocol": "protocol"
"direction": "direction"
}
]
}
profile
键唯一标识Profile
资源, ports
键表示Port
资源的嵌套列表。 Port
资源中的port
键唯一标识给定Profile
的端口。
这两个资源的建模如下:
PortModel = api.model("Port",
{
"port": fields.String(required=True),
"state": fields.String(required=True),
"protocol": fields.String(),
"direction": fields.String()
},
)
ProfileModel = api.model("Profile",
{
"profile": fields.String(required=True),
"ports": fields.List(fields.Nested(PortModel), required=True),
},
)
下面给出了两个资源的框架实现:
class Profile(Resource):
@api.expect(ProfileModel)
def post(self):
pass
class PortsList(Resource):
@api.expect([PortModel])
def post(self, profile):
pass
然后路线如下:
api.add_resource(Profile, "api/v1.0/profiles/")
api.add_resource(PortsList, "/api/v1.0/profiles/<profile>/ports")
问题:
当 POST 请求到达/api/v1.0/profiles/<profile>/ports
时,正文如下:
[
{
"port": "5687"
"state": "state"
"protocol": "protocol"
"direction": "direction"
}
]
后端应该为给定的配置文件创建Port
资源列表。
同样,当 POST 请求到达api/v1.0/profiles
时,正文如下:
{
"profile": "abcd"
"ports": [
{
"port": "5687"
"state": "state"
"protocol": "protocol"
"direction": "direction"
}
]
}
Profile
资源的post
方法是否可以自动调用和重用Port
资源的post
方法,将唯一标识Profile
资源的profile
传递给它? 如果是这样,我是否需要编写自己的代码或框架有能力处理这个?
在您的用例中,创建一个通用 Python 函数来处理端口逻辑并从两个端点调用此函数是否有意义?
def handle_ports(profile, ports):
... # Process your ports
class Profile(Resource):
@api.expect(ProfileModel)
def post(self):
handle_ports(
request.json.get('profile'),
request.json.get('ports')
)
... # Do additional stuff for this endpoint
class PortsList(Resource):
@api.expect([PortModel])
def post(self, profile):
handle_ports(
profile,
request.json.get('ports')
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.