[Python] MySQL OperationalError 2006 with FastAPI and SQLAlchemy during audio file upload

Discussão em 'Python' iniciado por Stack, Julho 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am encountering an issue while uploading audio files using FastAPI and SQLAlchemy in my Python application. The code is designed to handle user authentication, validate user IDs, and save metadate to a MySQL database. However, I am consistently getting the following OperationalError:

    pymysql.err.OperationalError: (2006, "MySQL server has gone away (ConnectionAbortedError(10053, 'An established connection was aborted by the software in your host machine', None, 10053, None))")


    I have already checked the MySQL server status, examined error logs, and reviewed connection parameters, but the issue persists. The error occurs during the audio_processor.save_audio_file_to_db method, which interacts with the MySQL database using SQLAlchemy.

    def save_audio_file_to_db(self, user_id: str, audio_file: UploadFile) -> str:
    log.info("Inside save_audio_file_to_db")
    try:
    # Generate a unique ID for the audio file
    audio_id = str(uuid4())

    # Create user-specific and audio-specific folders
    user_folder = f"user_{user_id}"
    audio_folder = os.path.join(COMMON_AUDIO_FOLDER, user_folder, audio_id)
    os.makedirs(audio_folder, exist_ok=True)

    # Save the uploaded audio file to the specified path
    audio_path = os.path.join(audio_folder, audio_file.filename)
    with open(audio_path, "wb") as audio_file_object:
    shutil.copyfileobj(audio_file.file, audio_file_object)

    # Call remove_silence function to remove silence from the audio before saving it to the path
    remove_silence(audio_path)

    # Calculate audio length using pydub
    audio = AudioSegment.from_file(audio_path)
    audio_length_in_seconds = len(audio) / 1000.0 # Convert milliseconds to seconds

    # Get current UTC time and convert it to Sri Lankan time
    utc_now = datetime.now(pytz.utc)
    sri_lankan_timezone = pytz.timezone('Asia/Colombo')
    lk_now = utc_now.astimezone(sri_lankan_timezone)

    # Metadata for the audio file
    metadata = {
    "size": os.path.getsize(audio_path),
    "utc_date": str(utc_now),
    "lk_date": str(lk_now),
    "audio_length_seconds": audio_length_in_seconds,
    }

    # Log metadata information to a file
    log_path = os.path.join(audio_folder, "metadata_log.txt")
    with open(log_path, "w") as log_file:
    for key, value in metadata.items():
    log_file.write(f"{key}: {value}\n")

    # Create an instance of the Audio model
    audio_instance = Audio(
    id=audio_id,
    user_id=user_id,
    path=audio_path,
    utc_date_created=metadata["utc_date"],
    lk_date_created=metadata["lk_date"],
    audio_length_seconds=metadata["audio_length_seconds"]
    )
    # Add the audio instance to the database and commit the changes
    self.db.add(audio_instance)
    self.db.commit()
    log.info("Save Audio in Db audio_id: "+audio_id)
    return audio_id```

    Continue reading...

Compartilhe esta Página