mgbam's picture
Update app.py
5e698c6 verified
raw
history blame
1.71 kB
from fastapi import FastAPI
from fastapi.responses import HTMLResponse, JSONResponse
import requests
import uvicorn
# Initialize FastAPI app
app = FastAPI()
# API endpoint for getting cryptocurrency prices from CoinGecko
API_URL = 'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin,ethereum,dogecoin&vs_currencies=usd'
# HTML template with HTMX integration
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/htmx.org"></script>
<title>Crypto Price Dashboard</title>
</head>
<body>
<h1>Cryptocurrency Prices</h1>
<div id="prices" hx-get="/api/prices" hx-trigger="every 10s">
<div>Loading...</div>
</div>
<script>
document.addEventListener('htmx:afterRequest', function(event) {
const pricesDiv = document.getElementById('prices');
const data = JSON.parse(event.detail.xhr.responseText);
pricesDiv.innerHTML = `
<div>Bitcoin: $${data.bitcoin.usd}</div>
<div>Ethereum: $${data.ethereum.usd}</div>
<div>Dogecoin: $${data.dogecoin.usd}</div>
`;
});
</script>
</body>
</html>
"""
@app.get("/", response_class=HTMLResponse)
def read_root():
return HTML_TEMPLATE
@app.get("/api/prices", response_class=JSONResponse)
def get_prices():
response = requests.get(API_URL)
response.raise_for_status()
return response.json()
if __name__ == "__main__":
# Run with: uvicorn this_file_name:app --host 0.0.0.0 --port 7860 --reload
uvicorn.run("this_file_name:app", host="0.0.0.0", port=7860, reload=True)