forked from zovos/bot_tg
72 lines
No EOL
1.5 KiB
Python
72 lines
No EOL
1.5 KiB
Python
from fastapi import FastAPI, Header, HTTPException
|
|
import requests
|
|
import time
|
|
|
|
app = FastAPI()
|
|
|
|
STORE_ID = 123456 # вставить storeId
|
|
API_TOKEN = "secret_token"
|
|
|
|
CACHE_TTL = 300 # 5 минут
|
|
cache = {
|
|
"data": None,
|
|
"timestamp": 0
|
|
}
|
|
|
|
SEARCH_PRODUCTS = [
|
|
"red bull",
|
|
"adrenaline rush",
|
|
"hoegaarden",
|
|
"baltika9",
|
|
]
|
|
|
|
@app.get("/magnit/products")
|
|
def get_products(x_token: str = Header(None)):
|
|
if x_token != API_TOKEN:
|
|
raise HTTPException(status_code=403, detail="Forbidden")
|
|
|
|
now = time.time()
|
|
|
|
# 🔹 кэш
|
|
if cache["data"] and now - cache["timestamp"] < CACHE_TTL:
|
|
return cache["data"]
|
|
|
|
headers = {
|
|
"User-Agent": "Mozilla/5.0",
|
|
"Accept": "application/json",
|
|
}
|
|
|
|
results = []
|
|
|
|
for query in SEARCH_PRODUCTS:
|
|
params = {
|
|
"query": query,
|
|
"storeId": STORE_ID,
|
|
"limit": 5
|
|
}
|
|
|
|
resp = requests.get(
|
|
"https://web-gateway.middle-api.magnit.ru/api/products/search",
|
|
headers=headers,
|
|
params=params,
|
|
timeout=10
|
|
)
|
|
|
|
if resp.status_code != 200:
|
|
continue
|
|
|
|
data = resp.json().get("data", [])
|
|
|
|
for item in data:
|
|
name = item.get("name", "")
|
|
price = item.get("price")
|
|
if price:
|
|
results.append({
|
|
"name": name,
|
|
"price": price
|
|
})
|
|
|
|
cache["data"] = results
|
|
cache["timestamp"] = now
|
|
|
|
return results |