80 lines
2.3 KiB
Python
80 lines
2.3 KiB
Python
|
from fastapi import FastAPI, HTTPException, Depends
|
||
|
from sqlalchemy.orm import Session
|
||
|
from app.database import SessionLocal
|
||
|
from app.schema import ADAUSDT, SHIBUSDT, BTCUSDT
|
||
|
|
||
|
# Inicjalizacja aplikacji FastAPI
|
||
|
app = FastAPI()
|
||
|
|
||
|
# Funkcja do tworzenia sesji bazy danych
|
||
|
def get_db():
|
||
|
db = SessionLocal()
|
||
|
try:
|
||
|
yield db
|
||
|
finally:
|
||
|
db.close()
|
||
|
|
||
|
# Endpoint GET: Pobranie listy coinów
|
||
|
@app.get("/coins/")
|
||
|
def get_coins(db: Session = Depends(get_db)):
|
||
|
# Lista modeli reprezentujących różne coiny
|
||
|
coin_models = {
|
||
|
"ADAUSDT": ADAUSDT,
|
||
|
"SHIBUSDT": SHIBUSDT,
|
||
|
"BTCUSDT": BTCUSDT,
|
||
|
}
|
||
|
|
||
|
coins_data = {}
|
||
|
|
||
|
# Iteracja po dostępnych coinach i pobranie ostatnich wartości
|
||
|
for coin_name, model in coin_models.items():
|
||
|
last_entry = db.query(model).order_by(model.timestamp.desc()).first()
|
||
|
if last_entry:
|
||
|
coins_data[coin_name] = {
|
||
|
"timestamp": last_entry.timestamp,
|
||
|
"open": last_entry.open,
|
||
|
"high": last_entry.high,
|
||
|
"low": last_entry.low,
|
||
|
"close": last_entry.close,
|
||
|
"volume": last_entry.volume,
|
||
|
}
|
||
|
|
||
|
if not coins_data:
|
||
|
raise HTTPException(status_code=404, detail="No coin data available.")
|
||
|
|
||
|
return coins_data
|
||
|
|
||
|
# Endpoint GET: Pobranie szczegółowych danych dla konkretnego coina
|
||
|
@app.get("/coins/{coin_name}")
|
||
|
def get_coin_details(coin_name: str, db: Session = Depends(get_db)):
|
||
|
# Mapowanie nazwy coina na model
|
||
|
coin_models = {
|
||
|
"ADAUSDT": ADAUSDT,
|
||
|
"SHIBUSDT": SHIBUSDT,
|
||
|
"BTCUSDT": BTCUSDT,
|
||
|
}
|
||
|
|
||
|
if coin_name not in coin_models:
|
||
|
raise HTTPException(status_code=404, detail=f"Coin {coin_name} not found.")
|
||
|
|
||
|
model = coin_models[coin_name]
|
||
|
|
||
|
# Pobierz wszystkie dane dla danego coina
|
||
|
coin_data = db.query(model).order_by(model.timestamp.desc()).all()
|
||
|
if not coin_data:
|
||
|
raise HTTPException(status_code=404, detail=f"No data available for {coin_name}.")
|
||
|
|
||
|
# Zwróć dane jako listę słowników
|
||
|
return [
|
||
|
{
|
||
|
"timestamp": entry.timestamp,
|
||
|
"open": entry.open,
|
||
|
"high": entry.high,
|
||
|
"low": entry.low,
|
||
|
"close": entry.close,
|
||
|
"volume": entry.volume,
|
||
|
}
|
||
|
for entry in coin_data
|
||
|
]
|
||
|
|