过滤重复请求

Filter for duplicate requests

当我经常访问 API 时,我得到了相同的答案!

这些请求在电报消息中重复!

如何过滤掉重复项?

def start_data():

    response = requests.get(
        url="http://api...."
        )
    
    result = []

    data = response.json()
    items = data.get("data")
    for i in items:
        id = i.get("id")
        name = i.get("name")
        price = i.get("price")
        
        result.append({
            "id":id,
            "name":name,
            "price":price
            })

    with open("input.json", "w") as f:
        json.dump(result, f)

我的 json 文件: 密钥 ID 是唯一的。

[
    {
        "id": "48683035",
        "name": "Cosmos",
        "price": 24.0
    },
    {
        "id": "48683027",
        "name": "Bar",
        "price": 13.0
    } ]

我的电报消息功能 每 5 秒安排一次

async def scheduled(wait_for): 
    while True: 
        await asyncio.sleep(wait_for)
        
        start_data()
        users = user_db.get_user()
        
        with open("input.json") as file:
            data = json.load(file)

        for s in users:
            if len(data) >= 1:
                for item in data:
                    send =f'{hbold("ID: ")}{item.get("id")}\n' \
                        f'{hbold("Name: ")}{item.get("name")}\n' \
                        f'{hbold("Price: ")}{item.get("price")}'
                    await bot.send_message(s[1], send)
            else:
                print("None data...")

您可以使用 set 来存储现有的 ids/objects。

all_ids = set()
for i in items:
    id = i.get("id")
    if id in all_ids:
        continue
    (...)
    all_ids.add(id)