【问题标题】:How to parse and filter a URL Web API in Django?如何在 Django 中解析和过滤 URL Web API?
【发布时间】: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


【解决方案1】:

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

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

您也可以使用 requests 库进行 POST 调用

【讨论】:

  • 您好 Raja,最后我无法完成您在上一篇文章中提供的代码。你有什么机会可以帮助我吗?
  • 请来chat我们继续讨论
  • 我尝试实现请求库来过滤我的发布请求,但似乎我创建的过滤器被忽略了。这是我的最新帖子stackoverflow.com/questions/45201628/…
  • 还有其他房间吗?
猜你喜欢
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2015-09-24
  • 1970-01-01
  • 2017-01-19
  • 1970-01-01
  • 2012-11-16
  • 1970-01-01
相关资源
最近更新 更多