Skip to content

Instantly share code, notes, and snippets.

@prasathmani
Last active May 26, 2023 17:20
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prasathmani/5d78a6126c3e1920ffb6fd591a759edb to your computer and use it in GitHub Desktop.
Save prasathmani/5d78a6126c3e1920ffb6fd591a759edb to your computer and use it in GitHub Desktop.
upload files to google drive using python
import requests, json
# Get refresh token from google drive api
# Generating a refresh token for DRIVE API calls using the OAuth playground
# https://www.youtube.com/watch?v=hfWe1gPCnzc
def getToken():
oauth = 'https://www.googleapis.com/oauth2/v4/token' # Google API oauth url
headers = {'content-type': 'application/x-www-form-urlencoded'}
data = {
'grant_type': 'refresh_token',
'client_id': '####',
'client_secret': '####',
'refresh_token': '####',
}
token = requests.post(oauth, headers=headers, data=data)
_key = json.loads(token.text)
return _key['access_token']
# Upload files to google drive using access token
def upload2Drive(files):
TOKEN_KEY = getToken()
headers = {"Authorization": "Bearer "+TOKEN_KEY}
upload = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers=headers,
files=files
)
print(upload.text)
if __name__ == '__main__':
file = "my-upload-test.zip" # change your file name
para = {
"name": file, #file name to be uploaded
"parents": ["####"] # make a folder on drive in which you want to upload files; then open that folder; the last thing in present url will be folder id
}
files = {
'data': ('metadata', json.dumps(para), 'application/json; charset=UTF-8'),
'file': ('application/zip',open("./"+file, "rb")) # replace 'application/zip' by 'image/png' for png images; similarly 'image/jpeg' (also replace your file name)
}
upload2Drive(files)
@ab9801
Copy link

ab9801 commented Mar 23, 2023

Awesome, was very useful for me

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