Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created May 28, 2022 00:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/a4cfbea4935b8c281d1f6abb91016705 to your computer and use it in GitHub Desktop.
Save tanaikech/a4cfbea4935b8c281d1f6abb91016705 to your computer and use it in GitHub Desktop.
Uploading Files to Google Drive with Asynchronous Process using Python

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)
    print(res)


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

Note

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

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment