問題
使用 flask_restful 撰寫 RESTFUL 介面,使用其中的 reqparse 進行引數決議時,一般按下面這樣使用的
from flask_restful import Resource, reqparse
class Scans(Resource):
def __init__(self):
timemode_choices = ('-T0', '-T1', '-T2', '-T3', '-T4', '-T5')
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('name', type=str, location='json')
self.reqparse.add_argument('port', type=str, location='json')
self.reqparse.add_argument('timemode', type=str, location='json', choices=timemode_choices)
super(Scans, self).__init__()
def post(self):
args = self.reqparse.parse_args()
print(args)
return args
def get(self):
pass
像上面這樣使用時,在請求中沒有設定的引數會被默認設定為 None,如下圖所示,分別是演示的列印的終端輸出和回傳回應中的輸出,


但是,有時候我們可能并不想要為未設定的引數設定默認None值,僅僅是想決議手動設定的引數,然后傳遞給其他的程式或命令,
解決方法
將 parser.args 中的各個引數的 store_missing 設定為 False,具體的方法就是添加一個 prepare_args_for_parser(parser) 函式,專門用來設定各個引數的store_missing=False. 修改后代碼如下,
from flask_restful import Resource, reqparse
# new
def prepare_args_for_parser(parser):
""" Modifies all the args of a Parser to better defaults. """
if not isinstance(parser, reqparse.RequestParser):
raise ValueError('Expecting a parser')
for arg in parser.args:
arg.store_missing = False
arg.help = "Error: {error_msg}. Field description: %s" % arg.help
return parser
class Scans(Resource):
def __init__(self):
timemode_choices = ('-T0', '-T1', '-T2', '-T3', '-T4', '-T5')
self.reqparse = reqparse.RequestParser()
self.reqparse.add_argument('name', type=str, location='json')
self.reqparse.add_argument('port', type=str, location='json')
self.reqparse.add_argument('timemode', type=str, location='json', choices=timemode_choices)
# new
self.reqparse = prepare_args_for_parser(self.reqparse)
super(Scans, self).__init__()
def post(self):
args = self.reqparse.parse_args()
print(args)
return args
def get(self):
pass
修改后的效果


可以看到沒有在請求中設定的 port 和 timemode 引數,沒有被默認設定為 None,
參考
https://github.com/flask-restful/flask-restful/issues/610
http://www.pythondoc.com/Flask-RESTful/reqparse.html#id2
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/256195.html
標籤:其他
上一篇:C/C++基礎知識:變數的作用域
