Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

python - flask restful: passing parameters to GET request

I want to create a resource that supports GET request in following way:

/bar?key1=val1&key2=val2

I tried this code, but it is not working

app = Flask(__name__)
api = Api(app)

class BarAPI(Resource):
    def get(key1, key2):
        return jsonify(dict(data=[key1, key2]))

api.add_resource(BarAPI, '/bar', endpoint='bar')

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit: reqparse is no longer the recommended way to do this with flask-restful!, but there is another example using marshmallow below.

The reqparse object is deprecated. See the docs or the second example in this post for alternatives.


Use reqparse. You can see another example in the flask-restful docs.

It performs validation on the parameters and does not require jsonify.

from flask import Flask
from flask_restful import Resource, Api, reqparse

app = Flask(__name__)
api = Api(app)

class BarAPI(Resource):
    def get(self):

        parser = reqparse.RequestParser()
        parser.add_argument('key1', type=str)
        parser.add_argument('key2', type=str)

        return parser.parse_args()

api.add_resource(BarAPI, '/bar', endpoint='bar')

if __name__ == '__main__':
    app.run(debug=True)

Another way is to use marshmallow.

You can use a Schema class,to validate request.args (for a PUT/POST request you might validate request.form)

from flask import Flask, request, abort
from flask_restful import Resource, Api
from marshmallow import Schema, fields


class BarQuerySchema(Schema):
    key1 = fields.Str(required=True)
    key2 = fields.Str(required=True)

app = Flask(__name__)
api = Api(app)
schema = BarQuerySchema()


class BarAPI(Resource):
    def get(self):
        errors = schema.validate(request.args)
        if errors:
            abort(400, str(errors))

        return 'ok'

api.add_resource(BarAPI, '/bar', endpoint='bar')

# omit of you intend to use `flask run` command
if __name__ == '__main__':
    app.run(debug=True)

This example requires that both parameters be present.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...