KeyError创建烧瓶API时的名称

时间:2018-06-19 09:19:23

标签: python api flask postman

我是Flask开发的新手,我正在尝试制作一个帖子API,但它只发布一次。我正在使用邮递员来测试这个api端点,它给了我这个错误跟踪:

Traceback (most recent call last):   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 2309, in __call__
    return self.wsgi_app(environ, start_response)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 2295, in wsgi_app
    response = self.handle_exception(e)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask_restful\__init__.py", line 273, in error_router
    return original_handler(e)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1741, in handle_exception
    reraise(exc_type, exc_value, tb)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\_compat.py", line 34, in reraise
    raise value.with_traceback(tb)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 2292, in wsgi_app
    response = self.full_dispatch_request()   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
    rv = self.handle_user_exception(e)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask_restful\__init__.py", line 273, in error_router
    return original_handler(e)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
    reraise(exc_type, exc_value, tb)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\_compat.py", line 34, in reraise
    raise value.with_traceback(tb)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
    rv = self.dispatch_request()   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\app.py", line 1799, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask_restful\__init__.py", line 480, in wrapper
    resp = resource(*args, **kwargs)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask\views.py", line 88, in view
    return self.dispatch_request(*args, **kwargs)   File "C:\Users\HPA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\flask_restful\__init__.py", line 595, in dispatch_request
    resp = meth(*args, **kwargs)   File "D:\Ride my app\ride_my_app\app\rides\managerides.py", line 46, in post
    if on.strip() == ridereq['offername'].strip(): KeyError: 'offername'

以下是我发布的代码:

rides_list = []
class GetRides(Resource):
    id=0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('offername', type=str, required=True)
        parser.add_argument('offerdetails', type=str, required=True)
        parser.add_argument('offerprice', type=float, required=True)
        #parser.add_argument('offerdby', type=float, required=True)
        parser.add_argument('token', location='headers')
        args = parser.parse_args()
         #check the token value if its available 
        if not args['token']:
            return make_response(jsonify({"message": "Token is missing"}), 401)
        decoded = decode_token(args['token'])
        if decoded["status"] == "Failure":
            return make_response(jsonify({"message": decoded["message"]}), 401)

        for user in my_users_list:
            if user['id'] == decoded['id']:
                if decoded['isDriver'] == "True":
                    on = args['offername']
                    od = args['offerdetails']
                    op = args['offerprice']
                    if on.strip() == "" or len(on.strip()) < 2:
                        return make_response(jsonify({"message": "Ride offer name  should be more than 2 letters"}), 400)

                    if re.compile('[!@#$^&*:;?><.]').match(on):
                        return make_response(jsonify({"message": "Invalid characters not allowed while creating a ride offer"}), 400)
                    global id
                    if len(rides_list)==0:
                        id = len(rides_list)+1
                    else:
                        id = id+1
                    new_request = AddRide(id,on,od,op)
                    for ridereq in rides_list:
                        if on.strip() == ridereq['offername'].strip():
                            return make_response(jsonify({"message": 'This ride offer already exists.'}), 400)

                    ridereq = json.loads(new_request.json())
                    rides_list.append(ridereq)

                    return make_response(jsonify({
                    'message': 'ride offers successfully created',
                    'status': 'success'},
                ), 201)
                return make_response(jsonify({"message": "Passenger is not authorized to create ride offers"}), 401)

        return make_response(jsonify({"message": "Please first create an account."}), 401)

根据错误消息,问题在于此行:

if on.strip() == ridereq['offername'].strip():

但我没有看到任何问题,可能是什么问题?

1 个答案:

答案 0 :(得分:0)

KeyError异常意味着您正在尝试引用不存在的字典中的密钥。在这种情况下,这意味着dict ridereq不包含密钥offername。如果它应该有这样一个键,那么你需要追踪你的程序中的任何错误导致ridereq['offername']永远不会被赋值。正如另一位意见提供者所建议的那样,在此行上方放置一份打印语句来检查ridereq的值是一个很好的起点。

此外,在同一行中,您错误地尝试将值分配给on.strip()。你不能这样做,因为on.strip()是一个函数调用,它返回一个字符串(即调用.strip() on方法的结果)。 foo.strip()不应出现在作业的左侧,因为您无法为字符串指定值。