我正在使用flask-restplus
创建一个RESTful API,该API连接到MongoDB集合并根据所调用的API提供信息。
API设计
HTTP GET
api/hashdoc/<str:product_id>
功能:为数据库中给定的list
提供所有product_id
的相关信息。
示例响应:
[
{
"product_id": "ABC","metadata": {
...
},"time_info": {
....
}
},{
"product_id": "ABC","metadata": {
...
},"time_info": {
...
}
}
]
HTTP GET
api/hashdoc/<str:product_id>?from=<str:ISO8601_timestamp>&to=<str:ISO8601_timestamp>
功能:应该提供使用数据库中的from
和to
值过滤的信息的JSON响应
示例响应:
{
"product_id": "ABC","metadata": {
...
},"time_info": {
...
}
}
当前实施
在我的hashdoc.py
中,我有以下代码:
from flask import request,abort
from flask_restplus import Namespace,Resource,fields,reqparse
from databases.documentdb import mongo
# API
api = Namespace('hashdoc',description='Hash Document Operations')
# REQUEST PARSER HERE
event_duration_parser = reqparse.RequestParser()
event_duration_parser.add_argument('from',type=str,required=True,help='ISO8601 UTC Timestamp (ms precision)')
event_duration_parser.add_argument('to',help='ISO8601 UTC Timestamp (ms precision)')
## hash_doc = api.model(....) removed for brewity
@api.route('/<product_id>')
@api.param('product_id','EPC Product ID')
@api.response(404,'No Values Exist for given Product ID.')
class HashDocListResource(Resource):
@api.marshal_list_with(hash_doc)
def get(self,product_id):
'''Fetch Hash Documents for given Product ID'''
print(product_id)
product_hash_doc = mongo.db['HashData'].find({'product_id': product_id},{'_id': 0})
list_product_hashdoc = list(product_hash_doc)
if len(list_product_hashdoc):
return list_product_hashdoc,200
else:
abort(404,{'error': 'No Values Exist for given Product ID.'})
@api.route('/<product_id>')
@api.param('product_id','No Values Exist for given Product ID & Time Range')
class HashDocResource(Resource):
@api.expect(event_duration_parser)
@api.marshal_with(hash_doc)
def get(self,product_id):
args = event_duration_parser.parse_args()
from_time = args.get('from')
to_time = args.get('to')
product_hash_doc_for_time_range = mongo.db['HashData'].find_one(
{'product_id': product_id,# Filtering based on TIMESTAMPS HERE
{'_id': 0})
if product_hash_doc_for_time_range:
return product_hash_doc_for_time_range,'No Values Exist for given Product ID & Time Range')
测试
使用curl
执行以下操作:
curl -XGET http://localhost:5000/api/hashdoc/ABC
为我提供了哈希文档的list
,并且行为正确。但是,当我执行以下操作时:
curl -XGET http://localhost:5000/api/hashdoc/ABC?from\="2019-11-05T14:32:31.830000Z"\&to\="2019-11-05T14:46:00.444000Z"
flask应用程序仍然查询api/hashdoc/ABC
并向我提供列表,而不是此处的过滤文档。
如何使用请求参数管理此类API?是否需要单独实施它们?
是否必须检查同一资源类中的from
和to
是否不是None
,然后执行查询?