-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
85 lines (65 loc) · 2.15 KB
/
Copy pathapp.py
File metadata and controls
85 lines (65 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import time
from flask import Flask, jsonify, render_template
import requests
app = Flask(__name__)
CACHE = {}
CACHE_TTL = 60 # secondi — limita le chiamate a CoinGecko e riduce la latenza percepita
COINGECKO_BASE = "https://api.coingecko.com/api/v3"
COINS = "bitcoin,ethereum,solana,cardano,dogecoin"
def get_cached(key):
entry = CACHE.get(key)
if entry and (time.time() - entry["ts"]) < CACHE_TTL:
return entry["data"]
return None
def set_cached(key, data):
CACHE[key] = {"data": data, "ts": time.time()}
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/prices")
def api_prices():
cache_key = "prices"
cached = get_cached(cache_key)
if cached:
return jsonify(cached)
try:
response = requests.get(
f"{COINGECKO_BASE}/coins/markets",
params={
"vs_currency": "usd",
"ids": COINS,
"order": "market_cap_desc",
"sparkline": "false",
},
timeout=8,
)
response.raise_for_status()
data = response.json()
set_cached(cache_key, data)
return jsonify(data)
except requests.exceptions.RequestException as e:
return jsonify({"error": str(e)}), 503
@app.route("/api/history/<coin_id>")
def api_history(coin_id):
# Allowlist per evitare che il parametro URL costruisca chiamate arbitrarie a CoinGecko
allowed = set(COINS.split(","))
if coin_id not in allowed:
return jsonify({"error": "Coin non supportata"}), 400
cache_key = f"history_{coin_id}"
cached = get_cached(cache_key)
if cached:
return jsonify(cached)
try:
response = requests.get(
f"{COINGECKO_BASE}/coins/{coin_id}/market_chart",
params={"vs_currency": "usd", "days": "7"},
timeout=8,
)
response.raise_for_status()
data = response.json()
set_cached(cache_key, data)
return jsonify(data)
except requests.exceptions.RequestException as e:
return jsonify({"error": str(e)}), 503
if __name__ == "__main__":
app.run(debug=True, port=5001)