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