The process cannot access the file because this file is occupied by another process:

34 Views Asked by At

I'm making a bot that includes the function of sending a file to a specific Google drive.I want to download the file, send it to google, and delete it, but at the moment of deletion, the error specified in the name occurs. In the future, it is planned to upload to hosting. Why does the file not close and gives an error? Is such an implementation suitable for deployment to hosting?

My piece of code looks like this:

import os
import pickle
from aiogram import types
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request


def getCreds():
    creds = None
    SCOPES = 'https://www.googleapis.com/auth/drive'

    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('client_secrets.json', SCOPES)
            creds = flow.run_local_server(port=8080)

        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    return creds


@dp.message_handler(
    content_types=types.ContentTypes.DOCUMENT, state=DDU.attach)
async def handle_DDU(message: types.Message, state: FSMContext):
    if message.document:
        try:
            logger.debug('Загрузка файла в google drive')
            await message.answer("Загрузка...")
            file = await bot.get_file(message.document.file_id)
            filename = message.document.file_name

            dwfile = await file.download(filename)

            creds = getCreds()
            service = build('drive', 'v3', credentials=creds, cache_discovery=False)
            async with state.proxy() as data:
                metadata = {
                    'name': f'ДДУ_{data.get("client_name")}',
                    'parents': ['1WUxAFLSOKYH0AUMWAO1IiBxj1oeJeg0C']
                    }
            media = MediaFileUpload(
                filename, mimetype=message.document.mime_type)
            request = service.files().create(
                body=metadata, media_body=media).execute()
            print(request)
            # await file.close()

            # Удаляем локальный файл после успешной загрузки на Google Drive

        except Exception as e:
            logger.info(f"Произошла ошибка: {e}")
            await message.reply(f"Произошла ошибка: {e}")

        finally:
            await message.answer("Успешно!")
            os.remove(filename)

    else:
        await message.answer("Пожалуйста, отправьте документ")
0

There are 0 best solutions below