[英]How to reuse the nested Resource methods in the encompassing Resource methods?
I have a resource called Profile
which nests a list of Port
resources like so:我有一个名为
Profile
的资源,它嵌套了一个Port
资源列表,如下所示:
{
"profile": "abcd"
"ports": [
{
"port": "5687"
"state": "state"
"protocol": "protocol"
"direction": "direction"
}
]
}
The profile
key uniquely identifies the Profile
resource and the ports
key represents the nested list of Port
resources. profile
键唯一标识Profile
资源, ports
键表示Port
资源的嵌套列表。 The port
key in the Port
resource uniquely identifies a port for the given Profile
. Port
资源中的port
键唯一标识给定Profile
的端口。
The two Resources are modeled like so:这两个资源的建模如下:
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),
},
)
The skeleton implementation of the two Resources is given below:下面给出了两个资源的框架实现:
class Profile(Resource):
@api.expect(ProfileModel)
def post(self):
pass
class PortsList(Resource):
@api.expect([PortModel])
def post(self, profile):
pass
Then the routes are as given below:然后路线如下:
api.add_resource(Profile, "api/v1.0/profiles/")
api.add_resource(PortsList, "/api/v1.0/profiles/<profile>/ports")
Question:问题:
When a POST request comes to /api/v1.0/profiles/<profile>/ports
with the following body:当 POST 请求到达
/api/v1.0/profiles/<profile>/ports
时,正文如下:
[
{
"port": "5687"
"state": "state"
"protocol": "protocol"
"direction": "direction"
}
]
the backend should create the list of Port
resources for the given profile.后端应该为给定的配置文件创建
Port
资源列表。
Similarly, when a POST request comes to api/v1.0/profiles
with the following body:同样,当 POST 请求到达
api/v1.0/profiles
时,正文如下:
{
"profile": "abcd"
"ports": [
{
"port": "5687"
"state": "state"
"protocol": "protocol"
"direction": "direction"
}
]
}
Is it possible for the post
method of Profile
resource to automatically invoke and reuse the post
method of Port
resource passing to it the profile
which uniquely identifies the Profile
resource? Profile
资源的post
方法是否可以自动调用和重用Port
资源的post
方法,将唯一标识Profile
资源的profile
传递给它? If so, do I need to write my own code or the framework has the capability to handle this?如果是这样,我是否需要编写自己的代码或框架有能力处理这个?
In your use case, does it make sense to create a common Python function to handle the logic of the ports, and call this function from both endpoints?在您的用例中,创建一个通用 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.