如何在Django中解析和过滤URL Web API?

时间:2017-06-13 05:31:38

标签: python django python-3.x rest django-rest-framework

我正在尝试过滤来自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 
},
...
}]

任何建议,方法或一段代码都表示赞赏。

1 个答案:

答案 0 :(得分:0)

您必须创建POST方法并使用对API的urllib post调用。

 <property name="JMS_PROD_TIME_TO_LIVE" scope="transport"
        type="STRING" value="15000"/>

或者,您可以使用requests库进行POST调用