Repository navigation
Expand file tree
/
Copy pathsimplified_app.py
More file actions
175 lines (149 loc) · 6.28 KB
/
Copy pathsimplified_app.py
File metadata and controls
175 lines (149 loc) · 6.28 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
"""
A simplified FastAPI app with Supabase integration in a single file.
Run this with: python simplified_app.py
"""
import uvicorn
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import httpx
from typing import List, Dict, Any
import os
import traceback
# Create FastAPI app
app = FastAPI(title="Simplified FastAPI App")
# Define Supabase credentials
SUPABASE_URL = "https://gbkhkbfbarsnpbdkxzii.supabase.co"
SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Imdia2hrYmZiYXJzbnBiZGt4emlpIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MzQzODAzNzMsImV4cCI6MjA0OTk1NjM3M30.mcOcC2GVEu_wD3xNBzSCC3MwDck3CIdmz4D8adU-bpI"
# Create templates directory if it doesn't exist
os.makedirs("templates", exist_ok=True)
# Create templates
templates = Jinja2Templates(directory="templates")
# HTML template content
index_html = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simplified FastAPI App</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 p-8">
<div class="max-w-4xl mx-auto">
<h1 class="text-3xl font-bold mb-6">Simplified FastAPI App with Supabase</h1>
<div class="bg-white rounded shadow p-6 mb-6">
<h2 class="text-xl font-semibold mb-4">Inventory from Supabase</h2>
<button id="fetchInventory" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded">
Fetch Inventory Models
</button>
<div id="result" class="mt-4 hidden overflow-auto"></div>
</div>
</div>
<script>
document.getElementById('fetchInventory').addEventListener('click', async function() {
const result = document.getElementById('result');
result.innerHTML = 'Loading...';
result.classList.remove('hidden');
try {
const response = await fetch('/api/inventory/models');
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Server error: ${response.status} - ${errorText}`);
}
const data = await response.json();
if (data.length === 0) {
result.innerHTML = '<p class="text-gray-700">No inventory models found.</p>';
} else {
// Create table
let html = '<div class="overflow-x-auto">';
html += '<table class="min-w-full bg-white border border-gray-300">';
// Headers
html += '<thead><tr class="bg-gray-100">';
const headers = Object.keys(data[0]);
headers.forEach(header => {
html += `<th class="px-4 py-2 text-left border-b border-gray-300">${header}</th>`;
});
html += '</tr></thead>';
// Rows
html += '<tbody>';
data.forEach(item => {
html += '<tr class="hover:bg-gray-50">';
headers.forEach(header => {
html += `<td class="px-4 py-2 border-b border-gray-300">${item[header] ?? 'N/A'}</td>`;
});
html += '</tr>';
});
html += '</tbody></table></div>';
result.innerHTML = html;
}
} catch (error) {
result.innerHTML = `<p class="text-red-500">Error: ${error.message}</p>`;
console.error(error);
}
});
</script>
</body>
</html>
"""
# Write the HTML template to the templates directory
with open("templates/index.html", "w") as f:
f.write(index_html)
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):
"""Global exception handler to show detailed error information"""
error_detail = {
"error": str(exc),
"traceback": traceback.format_exc()
}
return JSONResponse(
status_code=500,
content=error_detail
)
@app.get("/api/inventory/models", response_model=List[Dict[str, Any]])
async def get_inventory_models():
"""
Fetch inventory models from Supabase.
"""
try:
url = f"{SUPABASE_URL}/rest/v1/inventario_modelos"
headers = {
"apikey": SUPABASE_ANON_KEY,
"Authorization": f"Bearer {SUPABASE_ANON_KEY}",
"Content-Type": "application/json"
}
print(f"Making request to Supabase at: {url}")
print(f"Using headers: {headers}")
timeout = httpx.Timeout(30.0) # 30 seconds timeout
async with httpx.AsyncClient(timeout=timeout) as client:
response = await client.get(
url,
headers=headers,
params={"select": "*"}
)
print(f"Response status: {response.status_code}")
# Raise exception for non-200 responses
response.raise_for_status()
data = response.json()
print(f"Received {len(data)} records")
return data
except httpx.HTTPStatusError as e:
print(f"HTTP error occurred: {e}")
print(f"Response content: {e.response.text}")
raise HTTPException(
status_code=e.response.status_code,
detail=f"Supabase API error: {e.response.text}"
)
except Exception as e:
print(f"Unexpected error: {str(e)}")
print(traceback.format_exc())
raise HTTPException(
status_code=500,
detail=f"Failed to fetch inventory models: {str(e)}"
)
if __name__ == "__main__":
uvicorn.run("simplified_app:app", host="0.0.0.0", port=8000, reload=True)