[英]Flask restx model nested wildcard dict
我想知道我是否只是一個在這個問題上苦苦掙扎的人。
讓我們以 dict 為例:
data = {'totalSize': 3000, 'freq': 2400,
'distribution':
{'ram1': {'size': 200, 'status': 'OK'},
'ram2': {'size': 100, 'status': 'OK'}
}
}
請注意ram1/2是無法提前知道的動態鍵
問題,我的 api.model 應該是什么樣子? 我有:
wild = {"*": fields.Wildcard(fields.String())}
hw_memory = api.model('Memory', {
'totalSize': fields.Integer(description='total memory size in MB',
example=1024),
'freq': fields.Integer(description='Speed of ram in mhz', example=800),
'distribution': fields.Nested(wild),
})
它正在工作,但是它不會驗證“分發”以下的任何內容,換句話說,就像通配符一樣工作,任何東西都將被接受。 有沒有辦法以具有通配符動態鍵的方式嵌套字典?
首先, Wildcard
類型的字段接受字典值的定義,而不是鍵的定義,即fields.Wildcard(fields.String())
驗證字典值只能是字符串類型(在你的情況下你需要提供分布的定義)。
第二個錯誤是您將distribution
字段定義為Nested
object 而不是使用Wilcard
。
以下代碼應用於驗證目的:
DISTRIBUTION_MODEL = NAMESPACE.model("Distribution", dict(
size=fields.Integer(),
status=fields.String(),
))
MEMORY_MODEL = NAMESPACE.model("Memory", dict(
totalSize=fields.Integer(description='total memory size in MB',
example=1024),
freq=fields.Integer(description='Speed of ram in mhz', example=800),
distribution=fields.Wildcard(fields.Nested(DISTRIBUTION_MODEL))
))
不幸的是,它不適用於編組。 下一個代碼應該適用於封送處理,但不適用於驗證輸入有效負載:
OUTPUT_MEMORY_MODEL = NAMESPACE.model("OutputMemory", dict(
totalSize=fields.Integer(description='total memory size in MB',
example=1024),
freq=fields.Integer(description='Speed of ram in mhz', example=800),
distribution=flask_utils.fields.Nested(
NAMESPACE.model(
"distributions", {
"*": fields.Wildcard(
# DISTRIBUTION_MODEL is taken from previous snippet
fields.Nested(DISTRIBUTION_MODEL)
)
}
)
)
))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.