Uploading Files to Google Drive with Asynchronous Process using Python


This is a sample script for uploading files to Google Drive with asynchronous process using Python.

Sample script

import aiohttp
import asyncio
import json

folder_id = "###" # Please set the folder ID you want to put.
token = "###" # Please set your access token.
url = "https://www.googleapis.com/upload/drive/v3/files"

async def workers(file):

    async with aiohttp.ClientSession() as session:
        metadata = {"name": file["filename"], "parents": [folder_id]}
        data = aiohttp.FormData()
        data.add_field("metadata", json.dumps(metadata), content_type="application/json; charset=UTF-8")
        data.add_field("file", open(file["path"], "rb"))
        headers = {"Authorization": "Bearer " + token}
        params = {"uploadType": "multipart"}
        async with session.post(url, data=data, params=params, headers=headers) as resp:
            return await resp.json()

async def main():
    # Please set the filenames and the file paths as follows.
    fileList = [
        {"filename": "sample1", "path": "./sample1.png"},
    works = [asyncio.create_task(workers(e)) for e in fileList]
    res = await asyncio.gather(*works)

  • When this script is run, the files of fileList are uploaded to Google Drive with the asynchronous process.


  • This sample supposes that your access token can be used for uploading files to Google Drive using Drive API. Please be careful about this.