简体   繁体   中英

How to abort on unknown argument using flask-restful?

EDIT

This question is no longer relevant, since flask-restful new release can handle it by itself.

ORIGINAL QUESTION:

I have a flask-restful API, and I use reqparse in order to parse arguments. Now, I want to abort the request if the user uses an unknown argument.

Using reqparse, I can abort when I detect a known argument with a bad value, but it doesn't seem to have a default case where I could treat the others.

It would prevent users to contact me with "why isn't it working ?" when they are the one who are not using correct arguments.

How would you do?

EDIT: As asked, here is an example of view:

class myView(restful.Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('arg1', type=str, action='append')
        parser.add_argument('arg2', type=myType, action='append')
        args = parser.parse_args()
        result = dao.getResult(arg1, arg2)
        return jsonify(result)

api.add_resource(myView, '/view')

What I want is this: If a user goes to ip/view?bad_arg=bad then they get a 400 error.

Beginning with 0.3.1, you can pass strict=True to reqparse.parse_args . https://github.com/flask-restful/flask-restful/pull/358

reqparse does not provide a built in solution, but I was able to get over my problem by sub classing the reqparse parser.

class StrictParser(reqparse.RequestParser):

def parse_args(self, req=None):
    """Overide reqparse parser in order to fail on unknown argument
    """
    if req is None:
        req = request

    known_args = [arg.name for arg in self.args]
    for arg in request.args:
        if arg not in known_args:
            bad_arg = reqparse.Argument(arg)
            bad_arg.handle_validation_error("Unknown argument: %s" % arg)

    return reqparse.RequestParser.parse_args(self,req)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM