forked from zovos/bot_tg
Compare commits
1 commit
a85ab1c639
...
a5b0691a4e
| Author | SHA1 | Date | |
|---|---|---|---|
| a5b0691a4e |
1 changed files with 72 additions and 0 deletions
72
magnit_api.py
Normal file
72
magnit_api.py
Normal 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
|
||||||
Loading…
Reference in a new issue