blog_app_s1s86/app/api/db/database.py

46 lines
1.7 KiB
Python

```python
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()
```
1. We import the necessary modules from SQLAlchemy: `create_engine`, `declarative_base`, and `sessionmaker`.
2. We define the SQLite database URL using the `SQLALCHEMY_DATABASE_URL` variable, which points to the `blog_app.db` file in the current directory.
3. We create the SQLAlchemy engine using `create_engine` and pass the `SQLALCHEMY_DATABASE_URL` along with a `connect_args` parameter to handle a SQLite-specific thread issue.
4. We create a `SessionLocal` class using `sessionmaker`, which will be used to create database sessions.
5. We create a `Base` class using `declarative_base`, which will be used as the base class for all SQLAlchemy models.
6. Finally, we define a `get_db` function, which will be used as a dependency in our API routes to get a database session. This function creates a new session, yields it for use, and then closes the session after it's no longer needed.
```python
from fastapi import APIRouter, Depends
from app.api.db.database import get_db
from sqlalchemy.orm import Session
router = APIRouter()
@router.get("/blogs")
def get_blogs(db: Session = Depends(get_db)):
```
In this example, the `get_blogs` route gets a database session using the `get_db` dependency function, which can then be used to interact with the database using SQLAlchemy.