如何在烧瓶中获取请求 url "api/reviews?start_date=mm-dd-yyyy&end_date=mm-dd-yyyy"?
how to make get request url "api/reviews?start_date=mm-dd-yyyy&end_date=mm-dd-yyyy" in flask?
我是 Flask 的新手,我正在使用 Flask 构建 restful api。
class Review(Resource):
def get(self, id = None):
data = []
if id:
review_info = db.reviews.find_one({'_id': id})
if review_info:
return jsonify(review_info)
else:
return {"response": "no review found for {}".format(id)}
我目前的路线是
class Index(Resource):
def get(self):
return redirect(url_for("reviews"))
api = Api(app)
api.add_resource(Review, "/api/reviews/<int:id>", endpoint="id")
我想创建一个 get url "api/reviews?start_date=dd-mm-yyyy&end_date=dd-mm-yyyy" 我该怎么做?我不想创建 url 类型的 "api/start_date/../end_date/.."
这可以通过使用 marshmellow lib 来实现,这将使您能够方便地读取 get 请求中的查询参数。下面是您的请求的示例实现
from marshmallow import Schema, fields
class ReviewRequestFormat(Schema):
start_date=fields.Str(required=True)
end_date=fields.Str(required=True)
id=fields.Str(required=True)
class Review(Resource):
@use_kwargs(ReviewRequestFormat)
def get(self, **kwargs):
id=kwargs.get('id')
data = []
if id:
review_info = db.reviews.find_one({'_id': id})
if review_info:
return jsonify(review_info)
else:
return {"response": "no review found for {}".format(id)}
您的路线如下所示
class Index(Resource):
def get(self):
return redirect(url_for("reviews"))
api = Api(app)
api.add_resource(Review, "/api/reviews/", endpoint="id")
有关棉花糖的更多文档,您可以参考 -https://marshmallow.readthedocs.io/en/latest/
我是 Flask 的新手,我正在使用 Flask 构建 restful api。
class Review(Resource):
def get(self, id = None):
data = []
if id:
review_info = db.reviews.find_one({'_id': id})
if review_info:
return jsonify(review_info)
else:
return {"response": "no review found for {}".format(id)}
我目前的路线是
class Index(Resource):
def get(self):
return redirect(url_for("reviews"))
api = Api(app)
api.add_resource(Review, "/api/reviews/<int:id>", endpoint="id")
我想创建一个 get url "api/reviews?start_date=dd-mm-yyyy&end_date=dd-mm-yyyy" 我该怎么做?我不想创建 url 类型的 "api/start_date/../end_date/.."
这可以通过使用 marshmellow lib 来实现,这将使您能够方便地读取 get 请求中的查询参数。下面是您的请求的示例实现
from marshmallow import Schema, fields
class ReviewRequestFormat(Schema):
start_date=fields.Str(required=True)
end_date=fields.Str(required=True)
id=fields.Str(required=True)
class Review(Resource):
@use_kwargs(ReviewRequestFormat)
def get(self, **kwargs):
id=kwargs.get('id')
data = []
if id:
review_info = db.reviews.find_one({'_id': id})
if review_info:
return jsonify(review_info)
else:
return {"response": "no review found for {}".format(id)}
您的路线如下所示
class Index(Resource):
def get(self):
return redirect(url_for("reviews"))
api = Api(app)
api.add_resource(Review, "/api/reviews/", endpoint="id")
有关棉花糖的更多文档,您可以参考 -https://marshmallow.readthedocs.io/en/latest/