【问题标题】:POST API Request - Only Print if JSON Data in Response Has Changed - PythonPOST API 请求 - 仅在响应中的 JSON 数据已更改时打印 - Python
【发布时间】:2021-10-29 04:26:28
【问题描述】:

我正在尝试创建一种主动监控销售/列表的方法。我有一个创建的 POST api 将调用该网站,它目前正在成功提取包含已售商品、价格、时间、卖家和买家的 JSON 数据。

以下是 JSON 中返回的数据示例。

项目:1

价格:50 美元

发售日期:10/28/2021 10:00AM

卖家:约翰

买家:弗兰克

假设此脚本每 5 分钟运行一次,并打印出最后一笔交易。在 10:05,它看到商品 1 已售出,因此它打印出数据。在 10:10,没有新商品售出,所以它再次打印出 Item 1。我正在寻找一种仅在第 2 项出售时才打印出来的方法(也就是更新的 JSON 数据),但我无法找出在 python 中处理此逻辑的最佳方法。

您会只使用日期/时间减去最后 5 分钟吗?还是有更好的办法?

代码很简单:

asset_url = 'www.sample.com/api/'

seller_payload = json.dumps({
  "name": "find",
  "arguments": [
    {
      "database": "prod",
      "data": "SALES",
      "query": {
        "seller": {
          "$in": [
            "sellerid"
          ]
        },
      },
      "sort": {
        "epoch": {
          "$numberInt": "-1"
        }
      },
      "limit": {
          "$numberInt": "1"
      }
    }
  ],
  "service": "db"
})

seller_response = requests.request("POST", asset_url, headers=profile_headers, data=seller_payload)

asset_id = seller_response[0]['asset']
seller = seller_response[0]['seller']
price = seller_response[0]['price']
print(asset_id)
print(seller)
print(price)

【问题讨论】:

  • 请给出您的代码示例,因为这个问题的答案取决于您的代码的外观。
  • 考虑创建一个包含每个销售信息的类(每个交易都是一个实例),然后创建一个包含交易类的列表。打印最后添加的元素。
  • 我添加了一些示例代码
  • 需要上课吗?我的请求只返回最后一个值(最后售出的商品)。

标签: python


【解决方案1】:

如果脚本每 5 分钟运行一次,请将每个事务存储在一个文件中。像这样的:

from pickle import dump, loads
    
transactions = []
try:
    transactions = loads("transactions.txt") # try to read transactions from file.
except:
    print("An exception occurred.")
# Check if the last transaction is the same as it was five minutes ago.
if (not (transactions[-1]["asset"] == seller_response[0]["asset"] && transactions[-1]["seller"] == seller_response[0]["seller"] && transactions[-1]["soldDate"] == seller_response[0]["soldDate"] && transactions[-1]["buyer"] == seller_response[0]["buyer"] && transactions[-1]["item"] == seller_response[0]["item"])):
    print(seller_response[0])
    transactions.push(seller_response[0])
    dump(transactions,"transactions.txt")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 2018-07-20
    相关资源
    最近更新 更多