File size: 1,714 Bytes
5e698c6
 
40a414f
5e698c6
40a414f
5e698c6
 
40a414f
 
 
 
 
5e698c6
40a414f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5e698c6
40a414f
 
 
 
 
 
 
 
 
5e698c6
 
 
 
 
 
 
 
 
 
 
40a414f
5e698c6
 
 
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
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)