2017-06-13 27 views
0

我想過濾來自URL Web API的內容,我正在使用GET方法來獲取完整的數據集,然後對該響應應用一些過濾器,並獲得我期望的結果,但完整的檢索過程 - 過濾器 - 顯示結果大約需要3-5分鐘,這對用戶來說等待時間太長。我想應用POST方法直接從URL請求中過濾而不是檢索完整的數據集,這樣我就可以擺脫我的自定義過濾器並大大減少等待時間。我怎樣才能做到這一點?如何解析和過濾Django中的URL Web API?

這是當前代碼我有:

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 
}, 
... 
}] 

任何建議,方法或代碼片讚賞。

+0

你能告訴你的API視圖功能。告訴你如何使用queryset來獲得結果? –

+0

Hello Raja,你說的queryset是什麼意思?我根據網址api獲得了我的結果,但我無法過濾它。我更新了代碼,但我不確定這些信息是否會給您提供任何進一步的線索。讓我知道是否需要更多細節。 –

+0

我錯了。我以爲你自己創建了一個Web API。您提到了'POST'方法,您的API提供程序是否支持POST方法調用? –

回答

0

您必須創建POST方法並使用urllib post調用API。

class ChartData(APIView) 
    def post(self, request,format=None): 
     --- 
     # Your post call to API 

或者您可以使用requests庫,使POST調用

+0

您好Raja,最後我無法完成您在上一篇文章中提供的代碼。有什麼機會可以幫助我嗎? –

+0

當然...現在是什麼? –

+0

請來[聊天](https://chat.stackoverflow.com/rooms/146487/discussion-between-raja-simon-and-alejandro-ramos)我們繼續討論 –