Python flask restful:将参数传递给 GET 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30779584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
flask restful: passing parameters to GET request
提问by Rugnar
I want to create a resource that supports GET request in following way:
我想通过以下方式创建一个支持 GET 请求的资源:
/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!
谢谢!
采纳答案by Aditya
Flask can parse arguments through request
Flask 可以通过请求解析参数
from flask import request
You can use following lines in the block that requires GET parameters. GET is declared in @app.route()
declaration.
您可以在需要 GET 参数的块中使用以下行。GET 在声明中@app.route()
声明。
args = request.args
print (args) # For debugging
no1 = args['key1']
no2 = args['key2']
return jsonify(dict(data=[no1, no2])) # or whatever is required
回答by Paul Rooney
Edit: This is no longer the recommended way to do this with flask-restful!The reqparse
object is deprecated, see docsfor recommended alternative.
编辑:这不再是使用flask-restful 执行此操作的推荐方法!该reqparse
对象已弃用,请参阅文档以获取推荐的替代方案。
Use reqparse
. You can see another example in the flask-restful docs.
使用reqparse
. 您可以在flask-restful文档中看到另一个示例。
It performs validation on the parameters and does not require jsonify
.
它对参数执行验证,不需要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)
回答by severen
Since reqparse
is deprecated, here is a solution using the WebArgslibrary:
由于reqparse
已弃用,以下是使用WebArgs库的解决方案:
from flask import Flask
from flask_restful import Api, Resource, abort
from webargs import fields, validate
from webargs.flaskparser import use_kwargs, parser
app = Flask(__name__)
api = Api(app)
class Foo(Resource):
args = {
'bar': fields.Str(
required=True,
validate=validate.OneOf(['baz', 'qux']),
),
}
@use_kwargs(args)
def get(self, bar):
return {'bar': bar}
api.add_resource(Foo, '/foo', endpoint='foo')
# This error handler is necessary for usage with Flask-RESTful.
@parser.error_handler
def handle_request_parsing_error(err, req, schema, *, error_status_code, error_headers):
abort(error_status_code, errors=err.messages)
if __name__ == '__main__':
app.run(debug=True)
For more examples, see the Flask-RESTful examplein the WebArgs repository.
有关更多示例,请参阅WebArgs 存储库中的Flask-RESTful 示例。