Compare commits

...

1 commit

Author SHA1 Message Date
a5b0691a4e Добавить magnit_api.py 2026-02-20 10:08:22 +00:00

72
magnit_api.py Normal file
View file

@ -0,0 +1,72 @@
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