Spaces:
Sleeping
Sleeping
| import datetime | |
| from sqlalchemy import create_engine, Column, Integer, String, Boolean, DateTime | |
| from sqlalchemy.orm import sessionmaker | |
| from sqlalchemy.ext.declarative import declarative_base | |
| # Database file path. It will be created in your Space's persistent storage. | |
| DATABASE_URL = "sqlite:///./api_data.db" | |
| # SQLAlchemy setup | |
| engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| Base = declarative_base() | |
| # Define the ApiKey table model | |
| class ApiKey(Base): | |
| __tablename__ = "api_keys" | |
| id = Column(Integer, primary_key=True, index=True) | |
| key = Column(String, unique=True, index=True, nullable=False) | |
| is_active = Column(Boolean, default=True) | |
| usage_count = Column(Integer, default=0) | |
| created_at = Column(DateTime, default=datetime.datetime.utcnow) | |
| # Function to create the database and table | |
| def create_db_and_tables(): | |
| Base.metadata.create_all(bind=engine) | |
| # Dependency to get a database session | |
| def get_db(): | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() |