Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567891011121314151617181 unmodified line2021222324252627282930313233343536372 unmodified lines404142434445464748495051524 unmodified lines57585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118import sqlite3import pandas as pdfrom fastapi import FastAPI, Requestfrom fastapi.responses import HTMLResponseDB_PATH = "CarOwners_Full_Final.db"PAGE_SIZE = 200 # rows per pageapp = FastAPI()# Connect to SQLite DBconn = sqlite3.connect(DB_PATH, check_same_thread=False)cursor = conn.cursor()# ⚡ Create index for fast filteringcursor.execute("CREATE INDEX IF NOT EXISTS idx_city ON owners(City);")cursor.execute("CREATE INDEX IF NOT EXISTS idx_name ON owners(Name);")cursor.execute("CREATE INDEX IF NOT EXISTS idx_mobile ON owners([Mobile No]);")1 unmodified line# =========================# Fetch rows with pagination, city filter, and search# =========================def fetch_rows(offset: int = 0, city: str = "", search: str = ""):query = "SELECT * FROM owners WHERE 1=1"params = []# City filterif city:query += " AND LOWER(City) LIKE ?"params.append(f"%{city.lower()}%")# Search by Name or Mobileif search:query += " AND (LOWER(Name) LIKE ? OR [Mobile No] LIKE ?)"params.extend([f"%{search.lower()}%", f"%{search}%"])2 unmodified linesparams.extend([PAGE_SIZE, offset])df = pd.read_sql_query(query, conn, params=params)return df# =========================# Count total rows for pagination# =========================def count_rows(city: str = "", search: str = ""):query = "SELECT COUNT(*) FROM owners WHERE 1=1"params = []4 unmodified linesquery += " AND (LOWER(Name) LIKE ? OR [Mobile No] LIKE ?)"params.extend([f"%{search.lower()}%", f"%{search}%"])cursor.execute(query, params)return cursor.fetchone()[0]# =========================# Homepage with table, pagination, filter, and search# =========================@app.get("/", response_class=HTMLResponse)def home(request: Request):# Get query parametersoffset = int(request.query_params.get("offset", 0))city = request.query_params.get("city", "")search = request.query_params.get("search", "")# Fetch datadf = fetch_rows(offset, city, search)total = count_rows(city, search)# HTML pagehtml = """<html><head><title>Car Owners Data</title><style>table {border-collapse: collapse; width: 100%;}th, td {border: 1px solid black; padding: 5px; text-align: left;}th {background-color: #f2f2f2;}.filter {margin-bottom: 20px;}</style></head><body><h1>📋 Car Owners Data</h1><p>Total rows matching filter: {total}</p><div class="filter"><form method="get"><label>City: <input type="text" name="city" value="{city}"></label><label>Search (Name or Mobile): <input type="text" name="search" value="{search}"></label><input type="submit" value="Filter"><input type="hidden" name="offset" value="0"></form></div>""".format(total=total, city=city, search=search)# Tablehtml += df.to_html(index=False, escape=False)# Pagination buttonsnext_offset = offset + PAGE_SIZEprev_offset = max(offset - PAGE_SIZE, 0)html += "<div style='margin-top:20px;'>"if offset > 0:html += f'<a href="/?offset={prev_offset}&city={city}&search={search}"><button>Previous</button></a> 'if next_offset < total:html += f'<a href="/?offset={next_offset}&city={city}&search={search}"><button>Next</button></a>'html += "</div>"html += "</body></html>"return HTMLResponse(html)1234567891011121314151617181 unmodified line202122232425262728293031323334352 unmodified lines38394041424344454647484950514 unmodified lines5657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179import sqlite3import pandas as pdfrom fastapi import FastAPIfrom fastapi.responses import HTMLResponse, JSONResponseDB_PATH = "CarOwners_Full_Final.db"PAGE_SIZE = 200 # rows per pageapp = FastAPI()# Connect SQLiteconn = sqlite3.connect(DB_PATH, check_same_thread=False)cursor = conn.cursor()# ⚡ Create indexes for fast searchcursor.execute("CREATE INDEX IF NOT EXISTS idx_city ON owners(City);")cursor.execute("CREATE INDEX IF NOT EXISTS idx_name ON owners(Name);")cursor.execute("CREATE INDEX IF NOT EXISTS idx_mobile ON owners([Mobile No]);")1 unmodified line# =========================# API endpoint: fetch data chunk# =========================@app.get("/api/data")def get_data(offset: int = 0, city: str = "", search: str = ""):query = "SELECT * FROM owners WHERE 1=1"params = []if city:query += " AND LOWER(City) LIKE ?"params.append(f"%{city.lower()}%")if search:query += " AND (LOWER(Name) LIKE ? OR [Mobile No] LIKE ?)"params.extend([f"%{search.lower()}%", f"%{search}%"])2 unmodified linesparams.extend([PAGE_SIZE, offset])df = pd.read_sql_query(query, conn, params=params)return JSONResponse(df.to_dict(orient="records"))# =========================# API endpoint: count rows# =========================@app.get("/api/count")def get_count(city: str = "", search: str = ""):query = "SELECT COUNT(*) FROM owners WHERE 1=1"params = []4 unmodified linesquery += " AND (LOWER(Name) LIKE ? OR [Mobile No] LIKE ?)"params.extend([f"%{search.lower()}%", f"%{search}%"])if params:cursor.execute(query, tuple(params))else:cursor.execute(query)total = cursor.fetchone()[0]return {"total": total}# =========================# Frontend page# =========================@app.get("/", response_class=HTMLResponse)def home():html = """<html><head><title>Car Owners Data - Infinite Scroll</title><style>body { font-family: Arial; margin: 20px; }table { border-collapse: collapse; width: 100%; }th, td { border: 1px solid #ddd; padding: 8px; }th { background-color: #f2f2f2; }#loader { text-align: center; padding: 10px; }.filter { margin-bottom: 20px; }</style></head><body><h1>📋 Car Owners Data</h1><div class="filter"><label>City: <input type="text" id="city"></label><label>Search (Name or Mobile): <input type="text" id="search"></label><button onclick="applyFilter()">Apply</button></div><table id="data-table"><thead id="thead"><tr><th>Name</th><th>Mobile No</th><th>Address</th><th>Pin Code</th><th>City</th><th>Submodel</th><th>Model</th><th>Assettype</th><th>Misstatus</th><th>Tenor</th><th>Roi</th><th>Irr</th><th>Noadvemi</th><th>Emiamt</th><th>Netltv</th><th>Mfrsubded</th><th>Mfrsubnded</th><th>Dlrsubded</th><th>Dlrsubnded</th><th>Dsasubded</th><th>Promotiondesc</th><th>Product</th></tr></thead><tbody id="tbody"></tbody></table><div id="loader">Loading...</div><script>let offset = 0;const PAGE_SIZE = 200;let loading = false;let cityFilter = "";let searchFilter = "";async function loadData() {if (loading) return;loading = true;document.getElementById('loader').innerText = "Loading...";let response = await fetch(`/api/data?offset=${offset}&city=${cityFilter}&search=${searchFilter}`);let data = await response.json();let tbody = document.getElementById('tbody');for (let row of data) {let tr = document.createElement('tr');for (let key in row) {let td = document.createElement('td');td.innerText = row[key] === null ? "" : row[key];tr.appendChild(td);}tbody.appendChild(tr);}if (data.length < PAGE_SIZE) {document.getElementById('loader').innerText = "No more data";} else {document.getElementById('loader').innerText = "Scroll down to load more...";}offset += PAGE_SIZE;loading = false;}// Infinite scrollwindow.onscroll = function() {if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight - 50) {loadData();}}function applyFilter() {cityFilter = document.getElementById('city').value;searchFilter = document.getElementById('search').value;offset = 0;document.getElementById('tbody').innerHTML = "";loadData();}// Initial loadloadData();</script></body></html>"""return HTMLResponse(html)
app.py+116-55