繁体   English   中英

如何在包含的 Resource 方法中重用嵌套的 Resource 方法?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM