如何在烧瓶API中使用parser = reqparse.RequestParser()获取邮递员中的数组值?
收到错误消息:NoneType对象不可下标
这是我的代码:
class CreateUser(Resource):
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username', type = str)
args = parser.parse_args()
name = args['username'][0]
return name
except Exception as e:
x = str(e)
x.replace('\n', '')
return {'status' : 'failed', 'message' : str(x)}
finally:
if conn is not None:
conn.close()
我在使用此名称= args ['用户名'] [0]时遇到错误,我也尝试将其也设置为此名称= args [0] ['username'],但仍然出现错误,当我将其设为类似名称时= args ['username']邮递员回复null。请帮助我。
答案 0 :(得分:1)
使用此
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username[0]', type = str)
parser.add_argument('username[1]', type = str)
args = parser.parse_args()
name = args['username[0]']
return name
except Exception as e:
x = str(e)
x.replace('\n', '')
return {'status' : 'failed', 'message' : str(x)}
finally:
if conn is not None:
conn.close()
编辑多个参数 表单数据应该是这样的
username: "user1"
username: "user2"
username: "user3"
是的,您可以使用相同的键传递多个值
def post(self):
try:
conn = None
parser = reqparse.RequestParser()
parser.add_argument('username', type = str, action='append')
args = parser.parse_args()
name = args['username']
print(name) # ['user1', 'user2','user3'] you can traverse over this list