Spaces:
Sleeping
Sleeping
Download app.py from valent-p/volatile-api: direct link, hf CLI and curl.
- Browser
- Download file 2.22 kB
-
https://huggingface.co/spaces/valent-p/volatile-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/valent-p/volatile-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/valent-p/volatile-api/resolve/main/app.py
2.22 kB
| from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from sqlalchemy import create_engine, Column, Integer, String, DateTime | |
| from sqlalchemy.orm import declarative_base, sessionmaker, Session | |
| import datetime | |
| # --- DATABASE SETUP (SQLAlchemy + SQLite) --- | |
| SQLALCHEMY_DATABASE_URL = "sqlite:///./volatile.db" | |
| # check_same_thread=False is needed for SQLite in FastAPI | |
| engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}) | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| Base = declarative_base() | |
| # Define the Message Model | |
| class Message(Base): | |
| __tablename__ = "messages" | |
| id = Column(Integer, primary_key=True, index=True) | |
| sender = Column(String, index=True) | |
| content = Column(String) | |
| timestamp = Column(DateTime, default=datetime.datetime.utcnow) | |
| # Create the database tables | |
| Base.metadata.create_all(bind=engine) | |
| # Dependency to get DB session | |
| def get_db(): | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |
| # --- FASTAPI APP SETUP --- | |
| app = FastAPI(title="Volatile API") | |
| # Allow your Next.js Vercel frontend to connect | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # Update this to your Vercel domain later! | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --- ROUTES --- | |
| def read_root(): | |
| return {"status": "Volatile Backend is running!", "database": "SQLite connected"} | |
| # Example route to test saving a message to SQLite | |
| def create_test_message(sender: str, content: str, db: Session = Depends(get_db)): | |
| new_msg = Message(sender=sender, content=content) | |
| db.add(new_msg) | |
| db.commit() | |
| db.refresh(new_msg) | |
| return {"message": "Saved to Volatile memory", "data": new_msg} | |
| # --- WEBSOCKETS --- | |
| async def websocket_endpoint(websocket: WebSocket): | |
| await websocket.accept() | |
| try: | |
| while True: | |
| data = await websocket.receive_text() | |
| await websocket.send_text(f"Echo from Volatile Server: {data}") | |
| except WebSocketDisconnect: | |
| print("Client disconnected") |