29 lines
1.3 KiB
Python
29 lines
1.3 KiB
Python
Here's the `database.py` file for the `blog_app` FastAPI backend, configured with SQLite using SQLAlchemy:
|
|
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
SQLALCHEMY_DATABASE_URL = "sqlite:///./blog_app.db"
|
|
|
|
engine = create_engine(
|
|
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
|
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
Base = declarative_base()
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
Explanation:
|
|
|
|
1. We import the necessary modules from SQLAlchemy: `create_engine`, `declarative_base`, and `sessionmaker`.
|
|
2. We define the SQLite database URL using `SQLALCHEMY_DATABASE_URL = "sqlite:///./blog_app.db"`. This will create a new SQLite database file named `blog_app.db` in the current directory if it doesn't exist, or use the existing one if it does.
|
|
3. We create the SQLAlchemy engine using `create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})`. The `connect_args` parameter is required for SQLite to avoid threading issues.
|
|
5. We create a `Base` class using `declarative_base()`. This class will be used as the base class for defining database models. |