Spaces:
Runtime error
Runtime error
Download init_db.py from Quratulain1/Deploy-Backend: direct link, hf CLI and curl.
- Browser
- Download file 1.74 kB
-
https://huggingface.co/spaces/Quratulain1/Deploy-Backend/resolve/main/init_db.py
- Command line
-
hf download hf://spaces/Quratulain1/Deploy-Backend/init_db.py
-
curl -L -o init_db.py https://huggingface.co/spaces/Quratulain1/Deploy-Backend/resolve/main/init_db.py
1.74 kB
| import asyncio | |
| import os | |
| from sqlmodel import SQLModel | |
| from sqlalchemy.ext.asyncio import create_async_engine | |
| from sqlalchemy.pool import NullPool | |
| from dotenv import load_dotenv | |
| # Load environment variables | |
| load_dotenv(".env") | |
| # Get database URL from environment | |
| DATABASE_URL = os.getenv("DATABASE_URL", "postgresql+asyncpg://user:pass@localhost/dbname") | |
| # Handle URL conversion for asyncpg compatibility | |
| database_url = DATABASE_URL | |
| if database_url.startswith("postgresql://") and not database_url.startswith("postgresql+asyncpg://"): | |
| database_url = database_url.replace("postgresql://", "postgresql+asyncpg://", 1) | |
| # asyncpg doesn't support sslmode/channel_binding in the URL query string the same way | |
| # For Neon DB, we need to strip query parameters that asyncpg can't handle | |
| # This is the same approach used in test_conn.py which works | |
| if "?" in database_url: | |
| # Extract the base URL without query parameters for asyncpg compatibility | |
| base_url = database_url.split("?")[0] | |
| database_url = base_url | |
| # Create engine directly with no connection pooling for Neon serverless | |
| engine = create_async_engine( | |
| database_url, | |
| echo=False, | |
| future=True, | |
| poolclass=NullPool, # Use null pool for serverless | |
| connect_args={ | |
| "server_settings": { | |
| "application_name": "hack-2-web-app", | |
| } | |
| } | |
| ) | |
| # Important: Import models so SQLModel knows about them | |
| from models.task import Task | |
| from models.user import User | |
| async def init_db(): | |
| async with engine.begin() as conn: | |
| # Create all tables defined in SQLModel.metadata | |
| await conn.run_sync(SQLModel.metadata.create_all) | |
| print("Database tables created successfully.") | |
| if __name__ == "__main__": | |
| asyncio.run(init_db()) | |