【发布时间】:2017-11-14 17:34:41
【问题描述】:
我正在尝试过滤来自 URL Web API 的内容,并且我正在使用 GET 方法来获取完整的数据集,然后我对该响应应用了一些过滤器并获得了我想要的结果,但是完整的检索过程- 过滤器 - 显示结果大约需要 3-5 分钟,这对用户来说等待时间太长了。我想应用一个 POST 方法直接从 URL 请求中过滤,而不是检索完整的数据集,这样我就可以摆脱我的自定义过滤器并大大减少等待时间。我怎样才能做到这一点?
这是我当前的代码:
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from collections import Counter
from datetime import datetime, timedelta
import json, urllib.request, dateutil.parser, urllib.parse
class ChartData(APIView)
def get(self, request,format=None):
# Request access to the PO database and parse the JSON object
with urllib.request.urlopen(
"http://10.21.200.98:8081/T/ansdb/api/rows/PO/tickets?User_0001=Pat%20Trevor",
timeout=15) as url:
complete_data_user_0001 = json.loads(url.read().decode())
# Custom filter to the JSON response
# Count the number of times the user has created a PO between two given dates where the PO is not equal to N/A values
Counter([k['user_id'] for k in complete_data_user_0001 if
start_date < dateutil.parser.parse(
k.get('DateTime')) < end_date and
k['PO_value'] != 'N/A'])
return Response(data)
我想通过 POST 方法应用的过滤器是:
{
"filter": {
"filters": [
{
"field": "CreatedOnDate",
"operator": "gte",
"value": "2017-05-31 00:00:00"
},
{
"field": "CreatedOnDate",
"operator": "lte",
"value": "2017-06-04 00:00:00"
},
{
"field": "Triage_Subcategory",
"operator": "neq",
"value": "N/A"
}
],
"logic": "and"
}
}
JSON对象的结构是:
[{
user_id : 0001
CreatedOn: "2017-02-16 15:54:48",
Problem: "AVAILABILILTY",
VIP: "YES",
PO_value: N/A
},
{
user_id : 0001
CreatedOn: "2017-01-10 18:14:28",
Problem: "AVAILABILILTY",
VIP: "YES",
PO_value: 00098324
},
...
}]
感谢任何建议、方法或代码。
【问题讨论】:
-
你能展示你的API视图函数吗?说说你是如何使用 queryset 来获取结果的?
-
你好 Raja,你所说的查询集是什么意思?我根据 web url api 获得我的结果,但我无法过滤它。我更新了代码,但我不确定该信息是否为您提供任何进一步的线索。如果需要更多详细信息,请告诉我。
-
我弄错了。我以为你自己创建了一个 Web API。您提到了
POST方法,您的 API 提供者是否支持 POST 方法调用? -
是的,API 提供者支持 POST 方法,我能够通过使用 PostMan 中提到的过滤器来确认这一点。我能够使用该工具检索过滤后的数据。
标签: python django python-3.x rest django-rest-framework