48 lines
1.7 KiB
Python
48 lines
1.7 KiB
Python
Here's the `database.py` file for your FastAPI backend named 'blog_app' with SQLite configuration using SQLAlchemy:
|
|
|
|
```python
|
|
# app/api/db/database.py
|
|
|
|
from sqlalchemy import create_engine
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import sessionmaker
|
|
|
|
# SQLite database URL
|
|
SQLALCHEMY_DATABASE_URL = "sqlite:///./blog_app.db"
|
|
|
|
# Create the SQLAlchemy engine
|
|
engine = create_engine(
|
|
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
|
)
|
|
|
|
# Create a SessionLocal class for database sessions
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
# Create a Base class for models
|
|
Base = declarative_base()
|
|
```
|
|
|
|
This file contains the following components:
|
|
|
|
1. **SQLALCHEMY_DATABASE_URL**: The URL for the SQLite database file `blog_app.db`.
|
|
2. **engine**: The SQLAlchemy engine created using the `create_engine` function with the `SQLALCHEMY_DATABASE_URL` and a specific connection argument for SQLite (`check_same_thread=False`).
|
|
3. **SessionLocal**: A class that creates database sessions using the `sessionmaker` function. The `autocommit` and `autoflush` parameters are set to `False` for better control over transactions.
|
|
4. **Base**: A base class for defining SQLAlchemy models, created using the `declarative_base` function.
|
|
|
|
You can import and use these components in your FastAPI application as follows:
|
|
|
|
```python
|
|
# Import the required components
|
|
from app.api.db.database import SessionLocal, engine, Base
|
|
|
|
# Create a database session
|
|
db = SessionLocal()
|
|
|
|
# Use the session for database operations
|
|
# ...
|
|
|
|
# Close the session
|
|
db.close()
|
|
```
|
|
|
|
Make sure to create the `app/api/db/` directory in your project structure before adding this file. |