0

I am new in Flask development and I'm trying to make a post API but it posts only once. I am using postman to test this api endpoint, it gives me this error trace:

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'

Below is my code which does the posting :

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)

According to the error message the problem is in this line:

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

But I don't see any problem , what could be the problem?

  • can you `print(ridereq)` right before that line? It doesn't looks to me like it contains what you think it does – Ofer Sadan Jun 19 '18 at 09:27
  • Side note: in the future, please use code formatting instead of block quotes for posting tracebacks. It makes them more readable. – J. Taylor Jun 19 '18 at 09:37
  • when I print ridereq , the first time it shows nothing , but when I run again it shows the the dictionary –  Jun 19 '18 at 09:39
  • What I meant on my previous comment , is the that whenever I run in post , it first shows nothing , when I run again it shows the previous dictionary , when I run the 3rd time It shows again the previous previous dictionary , it lags behind per a run –  Jun 19 '18 at 09:46

1 Answers1

1

A KeyError exception means that you are attempting to reference a key in a dict that doesn't exist. In this case, it means that the dict ridereq does not contain a key offername. If it is supposed to have such a key, then you need to track down whatever bug in your program is causing ridereq['offername'] to never be assigned a value. As the other commenter suggested, throwing a print statement above this line to check the value of ridereq would be a good place to start.

Also, in that same line, you are incorrectly attempting to assign a value to on.strip(). You cannot do this because on.strip() is a function call which returns a string (i.e. the result of calling the .strip() method of on). foo.strip() should never appear on the left hand side of an assignment, because you can't assign a value to a string.

J. Taylor
  • 4,567
  • 3
  • 35
  • 55
  • Hey , I think the problem results from the comment I posted up , why is that like that do you have any clue ? –  Jun 19 '18 at 09:47
  • your answer is correct but I think the post lag is the problem. –  Jun 19 '18 at 10:06