Spaces:
Sleeping
Sleeping
File size: 10,235 Bytes
02ebf53 d2a98c6 8198489 8e064e1 d2a98c6 8e064e1 e9e401c 02ebf53 8e064e1 8198489 8e064e1 d2a98c6 02ebf53 e9e401c 8198489 8e064e1 8198489 8e064e1 8198489 8e064e1 8198489 8e064e1 8198489 8e064e1 8198489 8e064e1 8198489 8e064e1 7b108b2 d2a98c6 8e064e1 8198489 d2a98c6 8e064e1 d2a98c6 8e064e1 d2a98c6 7b108b2 8198489 d2a98c6 8e064e1 8198489 d2a98c6 02ebf53 8e064e1 7b108b2 d2a98c6 7b108b2 d2a98c6 8e064e1 c175e0c d2a98c6 7b108b2 d2a98c6 8e064e1 d2a98c6 8e064e1 d2a98c6 e9e401c 8198489 8e064e1 8198489 |
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 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 |
# app.py
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Union
import sqlite3
import os
import pandas as pd # Import pandas for CSV reading
# Define the Pydantic model for Item creation/update
class Item(BaseModel):
date: str
time: str
lat: float
lon: float
depth: float
ML: float
nstn: int
dmin: float
gap: int
trms: float
ERH: float
ERZ: float
fixed: str
nph: int
quality: str
# Define the Pydantic model for Item update specifically (allowing partial updates)
class ItemUpdate(BaseModel):
date: Union[str, None] = None
time: Union[str, None] = None
lat: Union[float, None] = None
lon: Union[float, None] = None
depth: Union[float, None] = None
ML: Union[float, None] = None
nstn: Union[int, None] = None
dmin: Union[float, None] = None
gap: Union[int, None] = None
trms: Union[float, None] = None
ERH: Union[float, None] = None
ERZ: Union[float, None] = None
fixed: Union[str, None] = None
nph: Union[int, None] = None
quality: Union[str, None] = None
app = FastAPI()
# Define the path for your SQLite database file
DATABASE_FILE = os.path.join(os.getcwd(), "data.db")
CSV_FILE_PATH = "GDMScatalog.csv" # Path to your CSV file
def get_db_connection():
"""Establishes and returns a SQLite database connection."""
try:
conn = sqlite3.connect(DATABASE_FILE)
conn.row_factory = sqlite3.Row
return conn
except sqlite3.Error as err:
print(f"Error connecting to database: {err}")
raise HTTPException(status_code=500, detail="Database connection error")
@app.on_event("startup")
async def startup_event():
"""
Initializes the database: creates the 'items' table if it doesn't exist.
Also, populates the database with data from the CSV file if the table is empty.
This runs once when the FastAPI application starts.
"""
conn = None
try:
conn = get_db_connection()
cursor = conn.cursor()
# Create table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
date TEXT NOT NULL,
time TEXT NOT NULL,
lat REAL NOT NULL,
lon REAL NOT NULL,
depth REAL NOT NULL,
ML REAL NOT NULL,
nstn INTEGER NOT NULL,
dmin REAL NOT NULL,
gap INTEGER NOT NULL,
trms REAL NOT NULL,
ERH REAL NOT NULL,
ERZ REAL NOT NULL,
fixed TEXT NOT NULL,
nph INTEGER NOT NULL,
quality TEXT NOT NULL
)
""")
conn.commit()
print(f"Database table 'items' checked/created successfully at {DATABASE_FILE}.")
# Check if the table is empty and populate from CSV
cursor.execute("SELECT COUNT(*) FROM items")
count = cursor.fetchone()[0]
if count == 0:
print("Table 'items' is empty. Populating from CSV file...")
if os.path.exists(CSV_FILE_PATH):
try:
df = pd.read_csv(CSV_FILE_PATH)
# Convert DataFrame to a list of tuples for insertion
# Ensure the order of columns matches the INSERT query
data_to_insert = [
(row['date'], row['time'], row['lat'], row['lon'], row['depth'],
row['ML'], row['nstn'], row['dmin'], row['gap'], row['trms'],
row['ERH'], row['ERZ'], row['fixed'], row['nph'], row['quality'])
for index, row in df.iterrows()
]
insert_query = """
INSERT INTO items (date, time, lat, lon, depth, ML, nstn, dmin, gap, trms, ERH, ERZ, fixed, nph, quality)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
cursor.executemany(insert_query, data_to_insert)
conn.commit()
print(f"Successfully inserted {len(data_to_insert)} records from {CSV_FILE_PATH}.")
except Exception as e:
print(f"Error populating database from CSV: {e}")
conn.rollback() # Rollback if CSV insertion fails
else:
print(f"CSV file not found at {CSV_FILE_PATH}. Database not populated.")
else:
print(f"Table 'items' already contains {count} records. Skipping CSV import.")
except Exception as e:
print(f"Error during database startup: {e}")
finally:
if conn:
conn.close()
@app.get("/")
async def root():
"""Root endpoint for the API."""
return {"message": "Welcome to the API! https://cwadayi-sqlite-api.hf.space/items/"}
@app.post("/items/")
async def create_item(item: Item):
"""Creates a new item in the database."""
conn = get_db_connection()
cursor = conn.cursor()
try:
query = """
INSERT INTO items (date, time, lat, lon, depth, ML, nstn, dmin, gap, trms, ERH, ERZ, fixed, nph, quality)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
cursor.execute(query, (
item.date,
item.time,
item.lat,
item.lon,
item.depth,
item.ML,
item.nstn,
item.dmin,
item.gap,
item.trms,
item.ERH,
item.ERZ,
item.fixed,
item.nph,
item.quality
))
conn.commit()
return {"message": "Item created successfully", "id": cursor.lastrowid}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500, detail=f"Error creating item: {e}")
finally:
cursor.close()
conn.close()
@app.get("/items/")
async def read_items():
"""Retrieves all items from the database."""
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM items")
items = cursor.fetchall()
return {"items": [dict(item) for item in items]}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error reading items: {e}")
finally:
cursor.close()
conn.close()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
"""Retrieves a single item by its ID."""
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("SELECT * FROM items WHERE id = ?", (item_id,))
item = cursor.fetchone()
if item is None:
raise HTTPException(status_code=404, detail="Item not found")
return dict(item)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error reading item: {e}")
finally:
cursor.close()
conn.close()
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: ItemUpdate):
"""Updates an existing item by its ID."""
conn = get_db_connection()
cursor = conn.cursor()
try:
updates = []
params = []
if item.date is not None:
updates.append("date = ?")
params.append(item.date)
if item.time is not None:
updates.append("time = ?")
params.append(item.time)
if item.lat is not None:
updates.append("lat = ?")
params.append(item.lat)
if item.lon is not None:
updates.append("lon = ?")
params.append(item.lon)
if item.depth is not None:
updates.append("depth = ?")
params.append(item.depth)
if item.ML is not None:
updates.append("ML = ?")
params.append(item.ML)
if item.nstn is not None:
updates.append("nstn = ?")
params.append(item.nstn)
if item.dmin is not None:
updates.append("dmin = ?")
params.append(item.dmin)
if item.gap is not None:
updates.append("gap = ?")
params.append(item.gap)
if item.trms is not None:
updates.append("trms = ?")
params.append(item.trms)
if item.ERH is not None:
updates.append("ERH = ?")
params.append(item.ERH)
if item.ERZ is not None:
updates.append("ERZ = ?")
params.append(item.ERZ)
if item.fixed is not None:
updates.append("fixed = ?")
params.append(item.fixed)
if item.nph is not None:
updates.append("nph = ?")
params.append(item.nph)
if item.quality is not None:
updates.append("quality = ?")
params.append(item.quality)
if not updates:
raise HTTPException(status_code=400, detail="No fields to update provided")
query = f"UPDATE items SET {', '.join(updates)} WHERE id = ?"
params.append(item_id)
cursor.execute(query, tuple(params))
conn.commit()
if cursor.rowcount == 0:
raise HTTPException(status_code=404, detail="Item not found")
return {"message": "Item updated successfully"}
except HTTPException:
raise
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500, detail=f"Error updating item: {e}")
finally:
cursor.close()
conn.close()
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
"""Deletes an item by its ID."""
conn = get_db_connection()
cursor = conn.cursor()
try:
cursor.execute("DELETE FROM items WHERE id = ?", (item_id,))
conn.commit()
if cursor.rowcount == 0:
raise HTTPException(status_code=404, detail="Item not found")
return {"message": "Item deleted successfully"}
except Exception as e:
conn.rollback()
raise HTTPException(status_code=500, detail=f"Error deleting item: {e}")
finally:
cursor.close()
conn.close() |