簡體   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