I’m working on a FastAPI project where I need to perform a bulk deletion of jobs using SQLAlchemy. The list of job IDs to be deleted is provided via a POST request from Postman. However, I’m encountering an error related to the synchronize_session parameter in the SQLAlchemy delete method. Here is my setup:
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
from typing import List
from dependency_injector.wiring import inject, Provide
from my_project.containers import Containers
from my_project.services import JobService
from my_project.models import BaseResponse
class JobIdsDTO(BaseModel):
job_ids: List[int]
organization_router = APIRouter()
@organization_router.post(
"/delete-bulk", summary="Delete bulk jobs by IDs", response_model=BaseResponse
)
@inject
async def delete_bulk_jobs(
job_ids_dto: JobIdsDTO,
authenticated_user: OAuth2PasswordBearer = Depends(validate_user),
job_service: JobService = Depends(Provide[Containers.job_service]),
):
job_ids = job_ids_dto.job_ids
if not authenticated_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Token expired",
headers={"WWW-Authenticate": "Bearer"},
)
if (
not hasattr(authenticated_user, "admin_id")
or authenticated_user.admin_id is None
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Login with admin account to continue",
headers={"WWW-Authenticate": "Bearer"},
)
return job_service.delete_bulk_jobs(
job_ids=job_ids
)
Service Layer:
class JobService:
def __init__(self, jobs_dao: JobsDAO):
self.jobs_dao = jobs_dao
def delete_bulk_jobs(self, job_ids: List[int]) -> int:
return self.jobs_dao.delete_bulk_jobs(job_ids)
DAO Layer
from sqlalchemy.orm import Session
from my_project.models import YourJobModel
class JobsDAO:
def __init__(self, db_session: Session):
self.db_session = db_session
def delete_bulk_jobs(self, job_ids: List[int]) -> int:
try:
result = (
self.db_session.query(YourJobModel)
.filter(YourJobModel.id.in_(job_ids))
.delete(synchronize_session="auto")
)
self.db_session.commit()
return result
except Exception as e:
self.db_session.rollback()
raise e
When I try to delete bulk jobs, I get the following error:
sqlalchemy.exc.ArgumentError: Valid strategies for session synchronization are 'auto', 'evaluate', 'fetch', False
1