我正在尝试上传文件,并使用Swagger UI以json格式接受用户的输入。我已经为相同的代码编写了以下代码。
upload_parser = api.parser()
upload_parser.add_argument('file', location='files',
type=FileStorage, required=True)
type = api.model("tax", {
"tax_form": fields.String()})
@api.route('/extraction')
@api.expect(upload_parser)
class extraction(Resource):
@api.expect(type)
def post(self):
tax_form= api.payload # json input string
print(tax_form['tax_form'])
args = upload_parser.parse_args() # upload a file
uploaded_file = args['file']
output = func_extract(uploaded_file,tax_form['tax_form'])
return output, 201
例如,当我单独运行上述内容时,例如,如果我仅上传文件或仅接受用户输入,则代码有效,但如果我一起执行它们。 tax_from返回 None 值,它不占用我通过Swagger UI输入的json值。
答案 0 :(得分:1)
我解决了问题。使用reqparse输入参数。参见下面的代码段
upload_parser = api.parser()
upload_parser.add_argument('file', location='files',
type=FileStorage, required=True)
parser = reqparse.RequestParser()
parser.add_argument('tax_form', required = True)
@api.route('/extraction')
@api.expect(upload_parser)
class extraction(Resource):
@api.expect(parser)
def post(self):
"""
extract the content
"""
args1 = parser.parse_args()
tax_form = args1['tax_form']
print(tax_form)
args = upload_parser.parse_args()
uploaded_file = args['file']
output = func_extract(uploaded_file,tax_form)
return output, 201
答案 1 :(得分:1)
我建议在api.expect中使用带有validate = True的模型和解析器列表(如果需要)。这将消除在类级别定义期望的查询参数(在您的情况下)的依赖性,因为您可能在同一条路由上具有GET / PUT / DELETE API,甚至可能不需要此参数。
已修改您的代码以更好地理解:
upload_parser = api.parser()
upload_parser.add_argument('file', location='files',
type=FileStorage, required=True)
tax_type = api.model("tax", {"tax_form": fields.String()})
@api.route('/extraction')
class extraction(Resource):
@api.expect(tax_type, upload_parser, validate=True)
def post(self):
tax_form= api.payload # json input string
print(tax_form['tax_form'])
args = upload_parser.parse_args() # upload a file
uploaded_file = args['file']
output = func_extract(uploaded_file,tax_form['tax_form'])
return output, 201
# This METHOD is now independent of your POST data expectations
def get(self):
output = {} # Some JSON
return output, 200
此外,请避免将python保留的关键字(如“类型”)用作变量。
希望这会有所帮助.. !!