Spaces:
Sleeping
Sleeping
Download database.py from abdullah9873/mock-api-mcp-server: direct link, hf CLI and curl.
- Browser
- Download file 2.18 kB
-
https://huggingface.co/spaces/abdullah9873/mock-api-mcp-server/resolve/main/database.py
- Command line
-
hf download hf://spaces/abdullah9873/mock-api-mcp-server/database.py
-
curl -L -o database.py https://huggingface.co/spaces/abdullah9873/mock-api-mcp-server/resolve/main/database.py
2.18 kB
| import os | |
| import json | |
| import sys | |
| from datetime import datetime | |
| from typing import List, Optional | |
| from dotenv import load_dotenv | |
| # CRITICAL: Load .env BEFORE reading DATABASE_URL | |
| # This file runs at import time, so we must load .env here | |
| load_dotenv() | |
| from sqlalchemy import String, DateTime, JSON, create_engine, Text | |
| from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, sessionmaker | |
| # Default to local SQLite, but support PostgreSQL via environment variable | |
| DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./mock_api.db") | |
| # Debug: Print which database we are connecting to (remove in production) | |
| print(f"[DB] Connecting to: {'Neon Postgres' if 'neon' in DATABASE_URL else 'Local SQLite'}", file=sys.stderr) | |
| # Neon/Postgres fix: SQLAlchemy requires postgresql:// instead of postgres:// | |
| if DATABASE_URL.startswith("postgres://"): | |
| DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://", 1) | |
| # Remove channel_binding parameter (not supported by psycopg2) | |
| if "channel_binding" in DATABASE_URL: | |
| # Remove &channel_binding=require or ?channel_binding=require | |
| import re | |
| DATABASE_URL = re.sub(r'[&?]channel_binding=[^&]*', '', DATABASE_URL) | |
| engine_args = {} | |
| if "sqlite" in DATABASE_URL: | |
| engine_args["connect_args"] = {"check_same_thread": False} | |
| # For Postgres, sslmode is already in the URL, no need for connect_args | |
| engine = create_engine(DATABASE_URL, **engine_args) | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| class Base(DeclarativeBase): | |
| pass | |
| class MockApiSchema(Base): | |
| __tablename__ = "mock_apis" | |
| id: Mapped[str] = mapped_column(String, primary_key=True, index=True) | |
| name: Mapped[str] = mapped_column(String) | |
| user_id: Mapped[str] = mapped_column(String, index=True) | |
| expires_at: Mapped[datetime] = mapped_column(DateTime) | |
| # Store the actual mock data as JSON for flexibility | |
| mock_data: Mapped[dict] = mapped_column(JSON, default={}) | |
| def init_db(): | |
| Base.metadata.create_all(bind=engine) | |
| def get_db(): | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |