Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import firebase_admin
|
| 2 |
+
from firebase_admin import credentials, db
|
| 3 |
+
from fastapi import FastAPI
|
| 4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
+
|
| 6 |
+
# Path to your Firebase service account key file
|
| 7 |
+
cred = credentials.Certificate("animvitals-firebase-adminsdk-sgfas-3c8e7f596c.json")
|
| 8 |
+
|
| 9 |
+
# Initialize the app with a service account, granting admin privileges
|
| 10 |
+
firebase_admin.initialize_app(cred, {
|
| 11 |
+
'databaseURL': 'https://animvitals-default-rtdb.firebaseio.com'
|
| 12 |
+
})
|
| 13 |
+
|
| 14 |
+
app = FastAPI()
|
| 15 |
+
|
| 16 |
+
# Allow CORS so your frontend can access this API
|
| 17 |
+
app.add_middleware(
|
| 18 |
+
CORSMiddleware,
|
| 19 |
+
allow_origins=["*"], # Allow all origins
|
| 20 |
+
allow_credentials=True,
|
| 21 |
+
allow_methods=["*"], # Allow all methods
|
| 22 |
+
allow_headers=["*"], # Allow all headers
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
@app.get("/latest-data")
|
| 26 |
+
async def get_latest_data():
|
| 27 |
+
# Reference to the 'animal_data' node
|
| 28 |
+
ref = db.reference('animal_data')
|
| 29 |
+
|
| 30 |
+
# Get the latest data
|
| 31 |
+
data = ref.order_by_key().limit_to_last(1).get()
|
| 32 |
+
|
| 33 |
+
# Since data is returned as a dictionary, get the first item (latest entry)
|
| 34 |
+
if data:
|
| 35 |
+
key = next(iter(data))
|
| 36 |
+
return data[key]
|
| 37 |
+
else:
|
| 38 |
+
return {"error": "No data found"}
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
import uvicorn
|
| 42 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|