HTTP GET API设计,它使用相同的端点,但在Flask中提供带有请求参数的过滤结果

我正在使用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>

功能应该提供使用数据库中的fromto值过滤的信息的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?是否需要单独实施它们?

是否必须检查同一资源类中的fromto是否不是None,然后执行查询?

youngssss 回答:HTTP GET API设计,它使用相同的端点,但在Flask中提供带有请求参数的过滤结果

  

Flask应用仍会查询api / hashdoc / ABC并向我提供   列表,而不是此处过滤的文档。

您创建了两个具有相同路由URL的资源类。因此它使用了它首先看到的那个(在您的情况下为HashDocListResource)。

  

如何使用请求参数管理此类API?是否需要   单独实施?

不,您不会仅为查询参数创建单独的资源类。

  

是否必须检查from和to是否不是None in   相同的资源类,然后执行查询?

是的。

我不确定您为什么在find中使用HashDocListResource,而在find_one中使用HashDocResource。在给定的时间范围内是否只能有一个HashDoc?

相同的示例实现。

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.expect(event_duration_parser)
    @api.marshal_list_with(hash_doc)
    def get(self,product_id):
        '''Fetch Hash Documents for given Product ID'''
        args = event_duration_parser.parse_args()
        from_time = args.get('from')
        to_time = args.get('to')

        query = {
            'product_id': product_id,}
        if from_time and to_time:
            query['your_time_stamp_field'] = {
                '$lte': to_time
            }
            query['your_time_stamp_field'] = {
                '$gte': from_time
            }
        projection = {'_id': 0}
        product_hash_docs = mongo.db['HashData'].find(query,projection)
        list_product_hashdoc = list(product_hash_docs)
        if len(list_product_hashdoc):
            return list_product_hashdoc,200
        else:
            abort(404,{'error': 'No Values Exist for given Product ID.'})

本文链接:https://www.f2er.com/3120920.html

大家都在问